Optional: nonstd to std

add-device-sharing
Kyle Schwarz 2022-07-22 01:27:39 -04:00
parent 1bb33156f7
commit 9ef01e2d3d
77 changed files with 175 additions and 7628 deletions

View File

@ -642,7 +642,7 @@ bool icsneo_getDigitalIO(const neodevice_t* device, neoio_t type, uint32_t numbe
return false;
}
const optional<bool> val = device->device->getDigitalIO(static_cast<icsneo::IO>(type), number);
const std::optional<bool> val = device->device->getDigitalIO(static_cast<icsneo::IO>(type), number);
if(!val.has_value())
return false;

View File

@ -150,22 +150,22 @@ std::shared_ptr<SerialNumberMessage> Communication::getSerialNumberSync(std::chr
return std::dynamic_pointer_cast<SerialNumberMessage>(m51);
}
optional< std::vector< optional<DeviceAppVersion> > > Communication::getVersionsSync(std::chrono::milliseconds timeout) {
std::optional< std::vector< std::optional<DeviceAppVersion> > > Communication::getVersionsSync(std::chrono::milliseconds timeout) {
static const std::shared_ptr<MessageFilter> filter = std::make_shared<MessageFilter>(Message::Type::DeviceVersion);
std::vector< optional<DeviceAppVersion> > ret;
std::vector< std::optional<DeviceAppVersion> > ret;
std::shared_ptr<Message> msg = waitForMessageSync([this]() {
return sendCommand(Command::GetMainVersion);
}, filter, timeout);
if(!msg) // Did not receive a message
return nullopt;
return std::nullopt;
auto ver = std::dynamic_pointer_cast<VersionMessage>(msg);
if(!ver) // Could not upcast for some reason
return nullopt;
return std::nullopt;
if(ver->ForChip != VersionMessage::MainChip || ver->Versions.size() != 1)
return nullopt;
return std::nullopt;
ret.push_back(ver->Versions.front());

View File

@ -1,10 +1,9 @@
#include "icsneo/communication/packet/canpacket.h"
#include "icsneo/communication/message/canerrorcountmessage.h"
#include "icsneo/platform/optional.h"
using namespace icsneo;
static optional<uint8_t> CAN_DLCToLength(uint8_t length, bool fd) {
static std::optional<uint8_t> CAN_DLCToLength(uint8_t length, bool fd) {
if (length <= 8)
return length;
@ -27,10 +26,10 @@ static optional<uint8_t> CAN_DLCToLength(uint8_t length, bool fd) {
}
}
return nullopt;
return std::nullopt;
}
static optional<uint8_t> CAN_LengthToDLC(size_t dataLength, bool fd)
static std::optional<uint8_t> CAN_LengthToDLC(size_t dataLength, bool fd)
{
if (dataLength <= 8)
return uint8_t(dataLength);
@ -52,7 +51,7 @@ static optional<uint8_t> CAN_LengthToDLC(size_t dataLength, bool fd)
return uint8_t(0xF);
}
return nullopt;
return std::nullopt;
}
std::shared_ptr<Message> HardwareCANPacket::DecodeToMessage(const std::vector<uint8_t>& bytestream) {
@ -94,7 +93,7 @@ std::shared_ptr<Message> HardwareCANPacket::DecodeToMessage(const std::vector<ui
msg->isCANFD = true;
msg->baudrateSwitch = data->header.BRS; // CAN FD Baudrate Switch
msg->errorStateIndicator = data->header.ESI;
const optional<uint8_t> lenFromDLC = CAN_DLCToLength(length, true);
const std::optional<uint8_t> lenFromDLC = CAN_DLCToLength(length, true);
if (lenFromDLC)
length = *lenFromDLC;
} else if(length > 8) { // This is a standard CAN frame with a length of more than 8
@ -133,7 +132,7 @@ bool HardwareCANPacket::EncodeFromMessage(const CANMessage& message, std::vector
}
const size_t dataSize = message.data.size();
optional<uint8_t> dlc = CAN_LengthToDLC(dataSize, message.isCANFD);
std::optional<uint8_t> dlc = CAN_LengthToDLC(dataSize, message.isCANFD);
if (!dlc.has_value()) {
report(APIEvent::Type::MessageMaxLengthExceeded, APIEvent::Severity::Error);
return false; // Too much data for the protocol

View File

@ -9,7 +9,7 @@ std::shared_ptr<VersionMessage> HardwareVersionPacket::DecodeMainToMessage(const
auto msg = std::make_shared<VersionMessage>(VersionMessage::MainChip);
msg->Versions.emplace_back();
optional<DeviceAppVersion>& version = msg->Versions.back();
std::optional<DeviceAppVersion>& version = msg->Versions.back();
version.emplace();
version->major = bytestream[1];
version->minor = bytestream[2];
@ -26,7 +26,7 @@ std::shared_ptr<VersionMessage> HardwareVersionPacket::DecodeSecondaryToMessage(
while(bytesLeft >= 3) {
const bool versionValid = bytestream[bytestream.size() - bytesLeft + 0];
msg->Versions.emplace_back();
optional<DeviceAppVersion>& version = msg->Versions.back();
std::optional<DeviceAppVersion>& version = msg->Versions.back();
if(versionValid) {
version.emplace();
version->major = bytestream[bytestream.size() - bytesLeft + 1];

View File

@ -3,7 +3,6 @@
#include "icsneo/api/eventmanager.h"
#include "icsneo/communication/command.h"
#include "icsneo/device/extensions/deviceextension.h"
#include "icsneo/platform/optional.h"
#include "icsneo/disk/fat.h"
#include "icsneo/communication/packet/wivicommandpacket.h"
#include "icsneo/communication/message/wiviresponsemessage.h"
@ -477,15 +476,15 @@ Network Device::getNetworkByNumber(Network::Type type, size_t index) const {
return Network::NetID::Invalid;
}
optional<uint64_t> Device::readLogicalDisk(uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) {
std::optional<uint64_t> Device::readLogicalDisk(uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) {
if(!into || timeout <= std::chrono::milliseconds(0)) {
report(APIEvent::Type::RequiredParameterNull, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
if(!isOpen()) {
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
std::lock_guard<std::mutex> lk(diskLock);
@ -499,7 +498,7 @@ optional<uint64_t> Device::readLogicalDisk(uint64_t pos, uint8_t* into, uint64_t
return ret;
});
if(!offset.has_value())
return nullopt;
return std::nullopt;
diskReadDriver->setVSAOffset(*offset);
}
@ -509,25 +508,25 @@ optional<uint64_t> Device::readLogicalDisk(uint64_t pos, uint8_t* into, uint64_t
return diskReadDriver->readLogicalDisk(*com, report, pos, into, amount, timeout);
}
optional<uint64_t> Device::writeLogicalDisk(uint64_t pos, const uint8_t* from, uint64_t amount, std::chrono::milliseconds timeout) {
std::optional<uint64_t> Device::writeLogicalDisk(uint64_t pos, const uint8_t* from, uint64_t amount, std::chrono::milliseconds timeout) {
if(!from || timeout <= std::chrono::milliseconds(0)) {
report(APIEvent::Type::RequiredParameterNull, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
if(!isOpen()) {
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
std::lock_guard<std::mutex> lk(diskLock);
return diskWriteDriver->writeLogicalDisk(*com, report, *diskReadDriver, pos, from, amount, timeout);
}
optional<bool> Device::isLogicalDiskConnected() {
std::optional<bool> Device::isLogicalDiskConnected() {
if(!isOpen()) {
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
// This doesn't *really* make sense here but because the disk read redirects the parser until it is done, we'll lock this
@ -536,16 +535,16 @@ optional<bool> Device::isLogicalDiskConnected() {
const auto info = com->getLogicalDiskInfoSync();
if (!info) {
report(APIEvent::Type::Timeout, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
return info->connected;
}
optional<uint64_t> Device::getLogicalDiskSize() {
std::optional<uint64_t> Device::getLogicalDiskSize() {
if(!isOpen()) {
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
// This doesn't *really* make sense here but because the disk read redirects the parser until it is done, we'll lock this
@ -554,16 +553,16 @@ optional<uint64_t> Device::getLogicalDiskSize() {
const auto info = com->getLogicalDiskInfoSync();
if (!info) {
report(APIEvent::Type::Timeout, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
return info->getReportedSize();
}
optional<uint64_t> Device::getVSAOffsetInLogicalDisk() {
std::optional<uint64_t> Device::getVSAOffsetInLogicalDisk() {
if(!isOpen()) {
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
std::lock_guard<std::mutex> lk(diskLock);
@ -575,7 +574,7 @@ optional<uint64_t> Device::getVSAOffsetInLogicalDisk() {
return diskReadDriver->readLogicalDisk(*com, report, pos, into, amount);
});
if(!offset.has_value())
return nullopt;
return std::nullopt;
if(diskReadDriver->getAccess() == Disk::Access::EntireCard && diskWriteDriver->getAccess() == Disk::Access::VSA) {
// We have mismatched drivers, we need to add an offset to the diskReadDriver
@ -585,7 +584,7 @@ optional<uint64_t> Device::getVSAOffsetInLogicalDisk() {
return *offset;
}
optional<bool> Device::getDigitalIO(IO type, size_t number /* = 1 */) {
std::optional<bool> Device::getDigitalIO(IO type, size_t number /* = 1 */) {
if(number == 0) { // Start counting from 1
report(APIEvent::Type::ParameterOutOfRange, APIEvent::Severity::Error);
return false;
@ -672,7 +671,7 @@ optional<bool> Device::getDigitalIO(IO type, size_t number /* = 1 */) {
};
report(APIEvent::Type::ParameterOutOfRange, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
bool Device::setDigitalIO(IO type, size_t number, bool value) {
@ -730,7 +729,7 @@ bool Device::setDigitalIO(IO type, size_t number, bool value) {
return false;
}
optional<double> Device::getAnalogIO(IO type, size_t number /* = 1 */) {
std::optional<double> Device::getAnalogIO(IO type, size_t number /* = 1 */) {
if(number == 0) { // Start counting from 1
report(APIEvent::Type::ParameterOutOfRange, APIEvent::Severity::Error);
return false;
@ -786,7 +785,7 @@ optional<double> Device::getAnalogIO(IO type, size_t number /* = 1 */) {
};
report(APIEvent::Type::ParameterOutOfRange, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
void Device::wiviThreadBody() {
@ -1001,15 +1000,15 @@ Lifetime Device::addSleepRequestedCallback(SleepRequestedCallback cb) {
});
}
optional<bool> Device::isSleepRequested() const {
std::optional<bool> Device::isSleepRequested() const {
if(!isOpen()) {
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
if(!supportsWiVI()) {
report(APIEvent::Type::WiVINotSupported, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
static std::shared_ptr<MessageFilter> filter = std::make_shared<MessageFilter>(Message::Type::WiVICommandResponse);
@ -1026,13 +1025,13 @@ optional<bool> Device::isSleepRequested() const {
if(!generic || generic->type != Message::Type::WiVICommandResponse) {
report(APIEvent::Type::NoDeviceResponse, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
const auto resp = std::static_pointer_cast<WiVI::ResponseMessage>(generic);
if(!resp->success || !resp->value.has_value()) {
report(APIEvent::Type::ValueNotYetPresent, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
return *resp->value;
@ -1188,18 +1187,18 @@ void Device::updateLEDState() {
com->sendCommand(Command::UpdateLEDState, args);
}
optional<EthPhyMessage> Device::sendEthPhyMsg(const EthPhyMessage& message, std::chrono::milliseconds timeout) {
std::optional<EthPhyMessage> Device::sendEthPhyMsg(const EthPhyMessage& message, std::chrono::milliseconds timeout) {
if(!isOpen()) {
report(APIEvent::Type::DeviceCurrentlyClosed, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
if(!getEthPhyRegControlSupported()) {
report(APIEvent::Type::EthPhyRegisterControlNotAvailable, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
if(!isOnline()) {
report(APIEvent::Type::DeviceCurrentlyOffline, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
std::vector<uint8_t> bytes;
@ -1210,11 +1209,11 @@ optional<EthPhyMessage> Device::sendEthPhyMsg(const EthPhyMessage& message, std:
if(!response) {
report(APIEvent::Type::NoDeviceResponse, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
auto retMsg = std::static_pointer_cast<EthPhyMessage>(response);
if(!retMsg) {
return nullopt;
return std::nullopt;
}
return make_optional<EthPhyMessage>(*retMsg);
return std::make_optional<EthPhyMessage>(*retMsg);
}

View File

@ -4,11 +4,11 @@
using namespace icsneo;
optional<uint16_t> IDeviceSettings::CalculateGSChecksum(const std::vector<uint8_t>& settings, optional<size_t> knownSize) {
std::optional<uint16_t> IDeviceSettings::CalculateGSChecksum(const std::vector<uint8_t>& settings, std::optional<size_t> knownSize) {
const uint16_t* p = reinterpret_cast<const uint16_t*>(settings.data());
size_t words = std::min(knownSize.value_or(0), settings.size());
if(words % 2 == 1)
return nullopt; // Somehow settings is not word aligned
return std::nullopt; // Somehow settings is not word aligned
words /= 2;
uint16_t gsCrc = 0;
@ -215,7 +215,7 @@ bool IDeviceSettings::apply(bool temporary) {
bytestream[2] = GS_VERSION >> 8;
bytestream[3] = (uint8_t)settings.size();
bytestream[4] = (uint8_t)(settings.size() >> 8);
optional<uint16_t> gsChecksum = CalculateGSChecksum(settings);
std::optional<uint16_t> gsChecksum = CalculateGSChecksum(settings);
if(!gsChecksum) {
// Could not calculate the checksum for some reason
report(APIEvent::Type::SettingsChecksumError, APIEvent::Severity::Error);
@ -321,7 +321,7 @@ bool IDeviceSettings::applyDefaults(bool temporary) {
bytestream[2] = GS_VERSION >> 8;
bytestream[3] = (uint8_t)settings.size();
bytestream[4] = (uint8_t)(settings.size() >> 8);
const optional<uint16_t> gsChecksum = CalculateGSChecksum(settings);
const std::optional<uint16_t> gsChecksum = CalculateGSChecksum(settings);
if(!gsChecksum) {
// Could not calculate the checksum for some reason
report(APIEvent::Type::SettingsChecksumError, APIEvent::Severity::Error);
@ -638,27 +638,27 @@ bool IDeviceSettings::canTerminationBeEnabledFor(Network net) const {
return false;
}
optional<bool> IDeviceSettings::isTerminationEnabledFor(Network net) const {
std::optional<bool> IDeviceSettings::isTerminationEnabledFor(Network net) const {
if(!settingsLoaded) {
report(APIEvent::Type::SettingsReadError, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
if(disabled) {
report(APIEvent::Type::SettingsNotAvailable, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
ICSNEO_UNALIGNED(const uint64_t*) terminationEnables = getTerminationEnables();
if(terminationEnables == nullptr) {
report(APIEvent::Type::TerminationNotSupportedDevice, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
const auto cmNet = net.getCoreMini();
if(!cmNet.has_value() || uint64_t(*cmNet) >= 64 || !isTerminationSupportedFor(net)) {
report(APIEvent::Type::TerminationNotSupportedNetwork, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
return (*terminationEnables >> uint64_t(*cmNet)) & 0x1;

View File

@ -4,7 +4,7 @@
using namespace icsneo;
using namespace icsneo::Disk;
optional<uint64_t> ReadDriver::readLogicalDisk(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> ReadDriver::readLogicalDisk(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) {
if(amount == 0)
return 0;
@ -12,7 +12,7 @@ optional<uint64_t> ReadDriver::readLogicalDisk(Communication& com, device_eventh
pos += vsaOffset;
// First read from the cache
optional<uint64_t> ret = readFromCache(pos, into, amount);
std::optional<uint64_t> ret = readFromCache(pos, into, amount);
if(ret == amount) // Full cache hit, we're done
return ret;
@ -99,15 +99,15 @@ void ReadDriver::invalidateCache(uint64_t pos, uint64_t amount) {
cache.clear();
}
optional<uint64_t> ReadDriver::readFromCache(uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds staleAfter) {
std::optional<uint64_t> ReadDriver::readFromCache(uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds staleAfter) {
if(cache.empty())
return nullopt; // Nothing in the cache
return std::nullopt; // Nothing in the cache
if(cachedAt + staleAfter < std::chrono::steady_clock::now())
return nullopt; // Cache is stale
return std::nullopt; // Cache is stale
if(pos > cachePos + cache.size() || pos < cachePos)
return nullopt; // Cache miss
return std::nullopt; // Cache miss
const auto cacheOffset = pos - cachePos;
const auto copyAmount = std::min<uint64_t>(cache.size() - cacheOffset, amount);

View File

@ -7,12 +7,12 @@ using namespace icsneo::Disk;
const uint64_t WriteDriver::RetryAtomic = std::numeric_limits<uint64_t>::max();
const APIEvent::Severity WriteDriver::NonatomicSeverity = APIEvent::Severity::EventInfo;
optional<uint64_t> WriteDriver::writeLogicalDisk(Communication& com, device_eventhandler_t report, ReadDriver& readDriver,
std::optional<uint64_t> WriteDriver::writeLogicalDisk(Communication& com, device_eventhandler_t report, ReadDriver& readDriver,
uint64_t pos, const uint8_t* from, uint64_t amount, std::chrono::milliseconds timeout) {
if(amount == 0)
return 0;
optional<uint64_t> ret;
std::optional<uint64_t> ret;
const uint32_t idealBlockSize = getBlockSizeBounds().second;

View File

@ -12,19 +12,19 @@
using namespace icsneo;
using namespace icsneo::Disk;
optional<uint64_t> ExtExtractorDiskReadDriver::readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> ExtExtractorDiskReadDriver::readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) {
if(amount > getBlockSizeBounds().second)
return nullopt;
return std::nullopt;
if(amount % getBlockSizeBounds().first != 0)
return nullopt;
return std::nullopt;
if(pos % getBlockSizeBounds().first != 0)
return nullopt;
return std::nullopt;
optional<uint64_t> ret;
std::optional<uint64_t> ret;
unsigned int attempts = 4;
while (attempts-- > 0)
{
@ -35,7 +35,7 @@ optional<uint64_t> ExtExtractorDiskReadDriver::readLogicalDiskAligned(Communicat
return ret;
}
optional<uint64_t> ExtExtractorDiskReadDriver::attemptReadLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> ExtExtractorDiskReadDriver::attemptReadLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) {
static std::shared_ptr<MessageFilter> NeoMemorySDRead = std::make_shared<MessageFilter>(Network::NetID::NeoMemorySDRead);
@ -44,7 +44,7 @@ optional<uint64_t> ExtExtractorDiskReadDriver::attemptReadLogicalDiskAligned(Com
uint64_t largeSectorCount = amount / SectorSize;
uint32_t sectorCount = uint32_t(largeSectorCount);
if (largeSectorCount != uint64_t(sectorCount))
return nullopt;
return std::nullopt;
std::mutex m;
std::condition_variable cv;
@ -181,7 +181,7 @@ optional<uint64_t> ExtExtractorDiskReadDriver::attemptReadLogicalDiskAligned(Com
Lifetime clearRedirect([&com, &lk] { lk.unlock(); com.clearRedirectRead(); });
if(error)
return nullopt;
return std::nullopt;
error = !com.sendCommand(ExtendedCommand::Extract, {
uint8_t(sector & 0xff),
@ -198,11 +198,11 @@ optional<uint64_t> ExtExtractorDiskReadDriver::attemptReadLogicalDiskAligned(Com
uint8_t((sectorCount >> 24) & 0xff),
});
if(error)
return nullopt;
return std::nullopt;
bool hitTimeout = !cv.wait_for(lk, timeout, [&]() { return error || amount == received; });
if(hitTimeout || error)
return nullopt;
return std::nullopt;
return amount;
}

View File

@ -8,7 +8,7 @@ using namespace icsneo;
// The FAT driver can only be accessed by one caller at a time, since it relies on globals
static std::mutex fatDriverMutex;
static std::function< optional<uint64_t>(uint64_t pos, uint8_t* into, uint64_t amount) > diskReadFn;
static std::function< std::optional<uint64_t>(uint64_t pos, uint8_t* into, uint64_t amount) > diskReadFn;
extern "C" DRESULT disk_read(BYTE, BYTE* buff, LBA_t sector, UINT count) {
static_assert(Disk::SectorSize == 512, "FatFs expects 512 byte sectors");
@ -32,17 +32,17 @@ static uint64_t ClusterToSector(const FATFS& fs, DWORD cluster) {
return fs.database + (LBA_t)fs.csize * (cluster - 2);
}
optional<uint64_t> Disk::FindVSAInFAT(std::function< optional<uint64_t>(uint64_t pos, uint8_t* into, uint64_t amount) > diskRead) {
std::optional<uint64_t> Disk::FindVSAInFAT(std::function< std::optional<uint64_t>(uint64_t pos, uint8_t* into, uint64_t amount) > diskRead) {
std::lock_guard<std::mutex> lk(fatDriverMutex);
diskReadFn = diskRead;
FATFS fs = {};
if (f_mount(&fs, (const TCHAR*)_TEXT(""), 0) != FR_OK)
return nullopt;
return std::nullopt;
FIL logData = {};
if (f_open(&logData, (const TCHAR*)_TEXT("0:\\LOG_DATA.VSA"), FA_READ) != FR_OK)
return nullopt;
return std::nullopt;
return ClusterToSector(fs, logData.obj.sclust) * uint64_t(Disk::SectorSize);
}

View File

@ -5,15 +5,15 @@
using namespace icsneo;
using namespace icsneo::Disk;
optional<uint64_t> NeoMemoryDiskDriver::readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> NeoMemoryDiskDriver::readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) {
static std::shared_ptr<MessageFilter> NeoMemorySDRead = std::make_shared<MessageFilter>(Network::NetID::NeoMemorySDRead);
if(pos % SectorSize != 0)
return nullopt;
return std::nullopt;
if(amount != SectorSize)
return nullopt;
return std::nullopt;
const uint64_t currentSector = pos / SectorSize;
auto msg = com.waitForMessageSync([&currentSector, &com] {
@ -36,23 +36,23 @@ optional<uint64_t> NeoMemoryDiskDriver::readLogicalDiskAligned(Communication& co
const auto sdmsg = std::dynamic_pointer_cast<NeoReadMemorySDMessage>(msg);
if(!sdmsg || sdmsg->data.size() != SectorSize) {
report(APIEvent::Type::PacketDecodingError, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
memcpy(into, sdmsg->data.data(), SectorSize);
return SectorSize;
}
optional<uint64_t> NeoMemoryDiskDriver::writeLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> NeoMemoryDiskDriver::writeLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, const uint8_t* atomicBuf, const uint8_t* from, uint64_t amount, std::chrono::milliseconds timeout) {
static std::shared_ptr<MessageFilter> NeoMemoryDone = std::make_shared<MessageFilter>(Network::NetID::NeoMemoryWriteDone);
if(pos % SectorSize != 0)
return nullopt;
return std::nullopt;
if(amount != SectorSize)
return nullopt;
return std::nullopt;
// Requesting an atomic operation, but neoMemory does not support it
// Continue on anyway but warn the caller
@ -75,7 +75,7 @@ optional<uint64_t> NeoMemoryDiskDriver::writeLogicalDiskAligned(Communication& c
}, NeoMemoryDone, timeout);
if(!msg)
return nullopt;
return std::nullopt;
return SectorSize;
}

View File

@ -3,26 +3,26 @@
using namespace icsneo;
using namespace icsneo::Disk;
optional<uint64_t> NullDriver::readLogicalDisk(Communication&, device_eventhandler_t report,
std::optional<uint64_t> NullDriver::readLogicalDisk(Communication&, device_eventhandler_t report,
uint64_t, uint8_t*, uint64_t, std::chrono::milliseconds) {
report(APIEvent::Type::DiskNotSupported, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
optional<uint64_t> NullDriver::readLogicalDiskAligned(Communication&, device_eventhandler_t report,
std::optional<uint64_t> NullDriver::readLogicalDiskAligned(Communication&, device_eventhandler_t report,
uint64_t, uint8_t*, uint64_t, std::chrono::milliseconds) {
report(APIEvent::Type::DiskNotSupported, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
optional<uint64_t> NullDriver::writeLogicalDisk(Communication&, device_eventhandler_t report, ReadDriver&,
std::optional<uint64_t> NullDriver::writeLogicalDisk(Communication&, device_eventhandler_t report, ReadDriver&,
uint64_t, const uint8_t*, uint64_t, std::chrono::milliseconds) {
report(APIEvent::Type::DiskNotSupported, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}
optional<uint64_t> NullDriver::writeLogicalDiskAligned(Communication&, device_eventhandler_t report,
std::optional<uint64_t> NullDriver::writeLogicalDiskAligned(Communication&, device_eventhandler_t report,
uint64_t, const uint8_t*, const uint8_t*, uint64_t, std::chrono::milliseconds) {
report(APIEvent::Type::DiskNotSupported, APIEvent::Severity::Error);
return nullopt;
return std::nullopt;
}

View File

@ -6,23 +6,23 @@
using namespace icsneo;
using namespace icsneo::Disk;
optional<uint64_t> PlasionDiskReadDriver::readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> PlasionDiskReadDriver::readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) {
static std::shared_ptr<MessageFilter> NeoMemorySDRead = std::make_shared<MessageFilter>(Network::NetID::NeoMemorySDRead);
if(amount > getBlockSizeBounds().second)
return nullopt;
return std::nullopt;
if(amount % getBlockSizeBounds().first != 0)
return nullopt;
return std::nullopt;
if(pos % getBlockSizeBounds().first != 0)
return nullopt;
return std::nullopt;
uint64_t largeSector = pos / SectorSize;
uint32_t sector = uint32_t(largeSector);
if (largeSector != uint64_t(sector))
return nullopt;
return std::nullopt;
std::mutex m;
std::condition_variable cv;
@ -62,7 +62,7 @@ optional<uint64_t> PlasionDiskReadDriver::readLogicalDiskAligned(Communication&
com.removeMessageCallback(cb);
if(hitTimeout)
return nullopt;
return std::nullopt;
return amount;
}

View File

@ -289,7 +289,7 @@ int main() {
if(!emisc.empty()) {
std::cout << "\tReading EMisc values..." << std::endl;
for(const auto& io : emisc) {
icsneo::optional<double> val = device->getAnalogIO(icsneo::IO::EMisc, io.number);
std::optional<double> val = device->getAnalogIO(icsneo::IO::EMisc, io.number);
std::cout << "\t\tEMISC" << io.number;
if(val.has_value())
std::cout << " - OK (" << val.value() << "V)" << std::endl;

View File

@ -56,7 +56,7 @@ public:
bool sendCommand(ExtendedCommand cmd, std::vector<uint8_t> arguments = {});
bool getSettingsSync(std::vector<uint8_t>& data, std::chrono::milliseconds timeout = std::chrono::milliseconds(50));
std::shared_ptr<SerialNumberMessage> getSerialNumberSync(std::chrono::milliseconds timeout = std::chrono::milliseconds(50));
optional< std::vector< optional<DeviceAppVersion> > > getVersionsSync(std::chrono::milliseconds timeout = std::chrono::milliseconds(50));
std::optional< std::vector< std::optional<DeviceAppVersion> > > getVersionsSync(std::chrono::milliseconds timeout = std::chrono::milliseconds(50));
std::shared_ptr<LogicalDiskInfoMessage> getLogicalDiskInfoSync(std::chrono::milliseconds timeout = std::chrono::milliseconds(50));
int addMessageCallback(const MessageCallback& cb);

View File

@ -5,7 +5,7 @@
#include "icsneo/communication/message/main51message.h"
#include "icsneo/communication/command.h"
#include "icsneo/platform/optional.h"
#include <optional>
#include <string>
namespace icsneo {
@ -29,8 +29,8 @@ public:
bool cmTooBig;
bool hidUsbState;
bool fpgaUsbState;
icsneo::optional<uint16_t> busVoltage;
icsneo::optional<uint16_t> deviceTemperature;
std::optional<uint16_t> busVoltage;
std::optional<uint16_t> deviceTemperature;
};
}

View File

@ -5,7 +5,7 @@
#include "icsneo/communication/message/message.h"
#include "icsneo/device/deviceversion.h"
#include "icsneo/platform/optional.h"
#include <optional>
namespace icsneo {
@ -19,7 +19,7 @@ public:
VersionMessage(Chip chip) : Message(Message::Type::DeviceVersion), ForChip(chip) {}
// nullopt here indicates invalid
std::vector< optional<DeviceAppVersion> > Versions;
std::vector< std::optional<DeviceAppVersion> > Versions;
// What chips the versions are for
const Chip ForChip;

View File

@ -5,8 +5,8 @@
#include "icsneo/communication/message/message.h"
#include "icsneo/communication/command.h"
#include "icsneo/platform/optional.h"
#include "icsneo/communication/packet/wivicommandpacket.h"
#include <optional>
#include <string>
namespace icsneo {
@ -24,9 +24,9 @@ class ResponseMessage : public Message {
public:
ResponseMessage() : Message(Message::Type::WiVICommandResponse) {}
bool success = true;
optional<Command> responseTo;
optional<int32_t> value;
optional<Info> info;
std::optional<Command> responseTo;
std::optional<int32_t> value;
std::optional<Info> info;
};
} // namespace WiVI

View File

@ -8,7 +8,7 @@ typedef uint8_t neonettype_t;
#ifdef __cplusplus
#include <ostream>
#include "icsneo/platform/optional.h"
#include <optional>
namespace icsneo {
@ -546,7 +546,7 @@ public:
}
return "Invalid Network";
}
static optional<CoreMini> GetCoreMiniNetworkFromNetID(NetID netid) {
static std::optional<CoreMini> GetCoreMiniNetworkFromNetID(NetID netid) {
switch(netid) {
case NetID::HSCAN:
return CoreMini::HSCAN;
@ -665,7 +665,7 @@ public:
case NetID::Ethernet2:
return CoreMini::Ethernet2;
default:
return nullopt;
return std::nullopt;
}
}
static NetID GetNetIDFromCoreMiniNetwork(CoreMini cm) {
@ -796,7 +796,7 @@ public:
Network(CoreMini cm) { setValue(GetNetIDFromCoreMiniNetwork(cm)); }
NetID getNetID() const { return value; }
Type getType() const { return type; }
optional<CoreMini> getCoreMini() const { return GetCoreMiniNetworkFromNetID(getNetID()); }
std::optional<CoreMini> getCoreMini() const { return GetCoreMiniNetworkFromNetID(getNetID()); }
friend std::ostream& operator<<(std::ostream& os, const Network& network) {
os << GetNetIDString(network.getNetID());
return os;

View File

@ -7,6 +7,7 @@
#include "icsneo/api/eventmanager.h"
#include <cstdint>
#include <memory>
#include <optional>
namespace icsneo {

View File

@ -10,6 +10,7 @@
#include <cstdint>
#include <atomic>
#include <type_traits>
#include <optional>
#include "icsneo/api/eventmanager.h"
#include "icsneo/api/lifetime.h"
#include "icsneo/device/neodevice.h"
@ -32,7 +33,6 @@
#include "icsneo/communication/message/flexray/control/flexraycontrolmessage.h"
#include "icsneo/communication/message/ethphymessage.h"
#include "icsneo/third-party/concurrentqueue/concurrentqueue.h"
#include "icsneo/platform/optional.h"
#include "icsneo/platform/nodiscard.h"
#define ICSNEO_FINDABLE_DEVICE_BASE(className, type) \
@ -114,10 +114,10 @@ public:
Progress
};
using OpenStatusHandler = std::function<Device::OpenDirective(OpenStatusType type, const std::string& status, optional<double> progress)>;
using OpenStatusHandler = std::function<Device::OpenDirective(OpenStatusType type, const std::string& status, std::optional<double> progress)>;
bool open(OpenFlags flags = {}, OpenStatusHandler handler =
[](OpenStatusType, const std::string&, optional<double>) { return Device::OpenDirective::Continue; });
[](OpenStatusType, const std::string&, std::optional<double>) { return Device::OpenDirective::Continue; });
virtual bool close();
virtual bool isOnline() const { return online; }
virtual bool isOpen() const { return com->isOpen(); }
@ -172,7 +172,7 @@ public:
* Upon failure, icsneo::nullopt will be returned and an error will be
* set in icsneo::GetLastError().
*/
optional<uint64_t> readLogicalDisk(uint64_t pos, uint8_t* into, uint64_t amount,
std::optional<uint64_t> readLogicalDisk(uint64_t pos, uint8_t* into, uint64_t amount,
std::chrono::milliseconds timeout = Disk::DefaultTimeout);
/**
@ -189,7 +189,7 @@ public:
* Upon failure, icsneo::nullopt will be returned and an error will be
* set in icsneo::GetLastError().
*/
optional<uint64_t> writeLogicalDisk(uint64_t pos, const uint8_t* from, uint64_t amount,
std::optional<uint64_t> writeLogicalDisk(uint64_t pos, const uint8_t* from, uint64_t amount,
std::chrono::milliseconds timeout = Disk::DefaultTimeout);
/**
@ -202,7 +202,7 @@ public:
* `icsneo::nullopt` will be returned if the device does not respond in a
* timely manner.
*/
optional<bool> isLogicalDiskConnected();
std::optional<bool> isLogicalDiskConnected();
/**
* Get the size of the connected logical disk in bytes.
@ -212,7 +212,7 @@ public:
* `icsneo::nullopt` will be returned if the device does not respond in a
* timely manner, or if the disk is disconnected/improperly configured.
*/
optional<uint64_t> getLogicalDiskSize();
std::optional<uint64_t> getLogicalDiskSize();
/**
* Get the offset to the VSA filesystem within the logical disk, represented
@ -224,7 +224,7 @@ public:
* `icsneo::nullopt` will be returned if the device does not respond in a
* timely manner, or if the disk is disconnected/improperly configured.
*/
optional<uint64_t> getVSAOffsetInLogicalDisk();
std::optional<uint64_t> getVSAOffsetInLogicalDisk();
/**
* Retrieve the number of Ethernet (DoIP) Activation lines present
@ -264,7 +264,7 @@ public:
* The index number starts counting at 1 to keep the numbers in sync
* with the numbering on the device, and is set to 1 by default.
*/
optional<bool> getDigitalIO(IO type, size_t number = 1);
std::optional<bool> getDigitalIO(IO type, size_t number = 1);
/**
* Set a digital IO to either a 1, if value is true, or 0 otherwise.
@ -288,7 +288,7 @@ public:
* The index number starts counting at 1 to keep the numbers in sync
* with the numbering on the device, and is set to 1 by default.
*/
optional<double> getAnalogIO(IO type, size_t number = 1);
std::optional<double> getAnalogIO(IO type, size_t number = 1);
typedef std::function< void(uint32_t startSector, uint32_t endSector) > NewCaptureCallback;
@ -319,7 +319,7 @@ public:
/**
* Check whether sleep has been requested by a VSSAL Wireless neoVI script.
*/
optional<bool> isSleepRequested() const;
std::optional<bool> isSleepRequested() const;
/**
* Signal to a running VSSAL Wireless neoVI script that we are ready for
@ -345,7 +345,7 @@ public:
/**
* For use by extensions only. A more stable API will be provided in the future.
*/
const std::vector<optional<DeviceAppVersion>>& getVersions() const { return versions; }
const std::vector<std::optional<DeviceAppVersion>>& getVersions() const { return versions; }
/**
* Some alternate communication protocols do not support DFU
@ -365,7 +365,7 @@ public:
*/
virtual bool supportsWiVI() const { return false; }
optional<EthPhyMessage> sendEthPhyMsg(const EthPhyMessage& message, std::chrono::milliseconds timeout = std::chrono::milliseconds(50));
std::optional<EthPhyMessage> sendEthPhyMsg(const EthPhyMessage& message, std::chrono::milliseconds timeout = std::chrono::milliseconds(50));
std::shared_ptr<Communication> com;
std::unique_ptr<IDeviceSettings> settings;
@ -377,12 +377,12 @@ protected:
device_eventhandler_t report;
std::mutex ioMutex;
optional<bool> ethActivationStatus;
optional<bool> usbHostPowerStatus;
optional<bool> backupPowerEnabled;
optional<bool> backupPowerGood;
std::array<optional<bool>, 6> miscDigital;
std::array<optional<double>, 2> miscAnalog;
std::optional<bool> ethActivationStatus;
std::optional<bool> usbHostPowerStatus;
std::optional<bool> backupPowerEnabled;
std::optional<bool> backupPowerGood;
std::array<std::optional<bool>, 6> miscDigital;
std::array<std::optional<double>, 2> miscAnalog;
// START Initialization Functions
Device(neodevice_t neodevice) : data(neodevice) {
@ -478,7 +478,7 @@ protected:
private:
neodevice_t data;
std::shared_ptr<ResetStatusMessage> latestResetStatus;
std::vector<optional<DeviceAppVersion>> versions;
std::vector<std::optional<DeviceAppVersion>> versions;
mutable std::mutex diskLock;
std::unique_ptr<Disk::ReadDriver> diskReadDriver;

View File

@ -3,7 +3,7 @@
#ifdef __cplusplus
#include "icsneo/platform/optional.h"
#include <optional>
#include <cstdint>
#include <array>

View File

@ -601,7 +601,7 @@ typedef struct {
#ifdef __cplusplus
#include "icsneo/communication/communication.h"
#include "icsneo/platform/optional.h"
#include <optional>
#include <iostream>
#include <atomic>
@ -612,7 +612,7 @@ public:
using TerminationGroup = std::vector<Network>;
static constexpr uint16_t GS_VERSION = 5;
static optional<uint16_t> CalculateGSChecksum(const std::vector<uint8_t>& settings, optional<size_t> knownSize = nullopt);
static std::optional<uint16_t> CalculateGSChecksum(const std::vector<uint8_t>& settings, std::optional<size_t> knownSize = std::nullopt);
static CANBaudrate GetEnumValueForBaudrate(int64_t baudrate);
static int64_t GetBaudrateValueForEnum(CANBaudrate enumValue);
@ -710,7 +710,7 @@ public:
* applied to the device, the current device status will be
* reflected here rather than the pending status.
*/
optional<bool> isTerminationEnabledFor(Network net) const;
std::optional<bool> isTerminationEnabledFor(Network net) const;
/**
* Enable or disable software switchable termination for a

View File

@ -3,10 +3,10 @@
#ifdef __cplusplus
#include "icsneo/platform/optional.h"
#include "icsneo/communication/communication.h"
#include "icsneo/api/eventmanager.h"
#include "icsneo/disk/diskdriver.h"
#include <optional>
#include <cstdint>
#include <chrono>
@ -19,7 +19,7 @@ namespace Disk {
*/
class ReadDriver : public virtual Driver {
public:
virtual optional<uint64_t> readLogicalDisk(Communication& com, device_eventhandler_t report,
virtual std::optional<uint64_t> readLogicalDisk(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout = DefaultTimeout);
void invalidateCache(uint64_t pos = 0,
@ -32,7 +32,7 @@ protected:
* The `pos` requested must be sector-aligned, and the `amount` must be
* within the block size bounds provided by the driver.
*/
virtual optional<uint64_t> readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
virtual std::optional<uint64_t> readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) = 0;
private:
@ -42,7 +42,7 @@ private:
static constexpr const std::chrono::milliseconds CacheTime = std::chrono::milliseconds(1000);
optional<uint64_t> readFromCache(uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds staleAfter = CacheTime);
std::optional<uint64_t> readFromCache(uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds staleAfter = CacheTime);
};
} // namespace Disk

View File

@ -3,12 +3,12 @@
#ifdef __cplusplus
#include "icsneo/platform/optional.h"
#include "icsneo/communication/communication.h"
#include "icsneo/api/eventmanager.h"
#include "icsneo/disk/diskreaddriver.h"
#include <cstdint>
#include <chrono>
#include <optional>
namespace icsneo {
@ -19,7 +19,7 @@ namespace Disk {
*/
class WriteDriver : public virtual Driver {
public:
virtual optional<uint64_t> writeLogicalDisk(Communication& com, device_eventhandler_t report, ReadDriver& readDriver,
virtual std::optional<uint64_t> writeLogicalDisk(Communication& com, device_eventhandler_t report, ReadDriver& readDriver,
uint64_t pos, const uint8_t* from, uint64_t amount, std::chrono::milliseconds timeout = DefaultTimeout);
protected:
@ -53,7 +53,7 @@ protected:
* is non-null, an APIEvent::AtomicOperationCompletedNonatomically
* should be reported with `NonatomicSeverity`.
*/
virtual optional<uint64_t> writeLogicalDiskAligned(Communication& com, device_eventhandler_t report,
virtual std::optional<uint64_t> writeLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, const uint8_t* atomicBuf, const uint8_t* from, uint64_t amount, std::chrono::milliseconds timeout) = 0;
};

View File

@ -28,10 +28,10 @@ private:
Access getPossibleAccess() const override { return Access::EntireCard; }
optional<uint64_t> readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) override;
optional<uint64_t> attemptReadLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> attemptReadLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout);
};

View File

@ -3,7 +3,7 @@
#ifdef __cplusplus
#include "icsneo/platform/optional.h"
#include <optional>
#include <cstdint>
#include <functional>
@ -11,7 +11,7 @@ namespace icsneo {
namespace Disk {
optional<uint64_t> FindVSAInFAT(std::function< optional<uint64_t>(uint64_t pos, uint8_t* into, uint64_t amount) > diskRead);
std::optional<uint64_t> FindVSAInFAT(std::function< std::optional<uint64_t>(uint64_t pos, uint8_t* into, uint64_t amount) > diskRead);
} // namespace Disk

View File

@ -30,10 +30,10 @@ private:
Access getPossibleAccess() const override { return Access::VSA; }
optional<uint64_t> readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) override;
optional<uint64_t> writeLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> writeLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, const uint8_t* atomicBuf, const uint8_t* from, uint64_t amount, std::chrono::milliseconds timeout) override;
};

View File

@ -18,9 +18,9 @@ namespace Disk {
*/
class NullDriver : public ReadDriver, public WriteDriver {
public:
optional<uint64_t> readLogicalDisk(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> readLogicalDisk(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout = DefaultTimeout) override;
optional<uint64_t> writeLogicalDisk(Communication& com, device_eventhandler_t report, ReadDriver& readDriver,
std::optional<uint64_t> writeLogicalDisk(Communication& com, device_eventhandler_t report, ReadDriver& readDriver,
uint64_t pos, const uint8_t* from, uint64_t amount, std::chrono::milliseconds timeout = DefaultTimeout) override;
std::pair<uint32_t, uint32_t> getBlockSizeBounds() const override {
static_assert(SectorSize <= std::numeric_limits<uint32_t>::max(), "Incorrect sector size");
@ -31,9 +31,9 @@ public:
private:
Access getPossibleAccess() const override { return Access::None; }
optional<uint64_t> readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) override;
optional<uint64_t> writeLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> writeLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, const uint8_t* atomicBuf, const uint8_t* from, uint64_t amount, std::chrono::milliseconds timeout) override;
};

View File

@ -27,7 +27,7 @@ private:
Access getPossibleAccess() const override { return Access::EntireCard; }
optional<uint64_t> readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
std::optional<uint64_t> readLogicalDiskAligned(Communication& com, device_eventhandler_t report,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds timeout) override;
};

View File

@ -1,23 +0,0 @@
#ifndef __ICSNEO_OPTIONAL_H_
#define __ICSNEO_OPTIONAL_H_
#include "icsneo/third-party/optional-lite/include/nonstd/optional.hpp"
/**
* We use icsneo::optional throughout the C++ API to allow for polyfilling
* std::optional into C++11 and C++14 environments. In a C++17 or better
* environment, icsneo::optional will be an alias of std::optional.
*/
namespace icsneo {
using nonstd::optional;
using nonstd::bad_optional_access;
using nonstd::make_optional;
using nonstd::nullopt;
using nonstd::nullopt_t;
} // namespace icsneo
#endif

View File

@ -6,7 +6,7 @@
#include "icsneo/communication/driver.h"
#include "icsneo/device/neodevice.h"
#include "icsneo/api/eventmanager.h"
#include "icsneo/platform/optional.h"
#include <optional>
#include <chrono>
#include <sys/stat.h>
#include <stdint.h>
@ -39,7 +39,7 @@ public:
private:
neodevice_t& device;
int fd = -1;
optional<ino_t> disallowedInode;
std::optional<ino_t> disallowedInode;
std::atomic<bool> modeChanging{false};
std::thread modeChangeThread;
std::mutex modeChangeMutex;

View File

@ -7,7 +7,7 @@
#include "icsneo/device/founddevice.h"
#include "icsneo/communication/driver.h"
#include "icsneo/api/eventmanager.h"
#include "icsneo/platform/optional.h"
#include <optional>
#include <string>
namespace icsneo {
@ -127,11 +127,11 @@ private:
uint8_t* vbase = nullptr;
volatile ComHeader* header = nullptr;
optional<MsgQueue> in;
std::optional<MsgQueue> in;
std::mutex outMutex;
optional<MsgQueue> out;
optional<Mempool> outMemory;
std::optional<MsgQueue> out;
std::optional<Mempool> outMemory;
};
}

View File

@ -1,31 +0,0 @@
# Configuration file for EditorConfig, see https://EditorConfig.org
# Ignore any other files further up in the file system
root = true
# All files:
[*]
# Let git determine line ending: end_of_line = lf
charset = utf-8
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
# Markdown files: keep trailing space-pair as line-break
[*.md]
trim_trailing_whitespace = false
# Python scripts:
[*.py]
# YAML scripts:
[*.yml]
indent_size = 2
# Makefiles: Tab indentation (no size specified)
[Makefile]
indent_style = tab
# C, C++ source files:
[*.{h,hpp,c,cpp}]

View File

@ -1,26 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto
# Custom for CodeBlocks
*.cbp text eol=lf
*.workspace text eol=lf
# Custom for Visual Studio
*.cs diff=csharp
*.sln merge=union
*.csproj merge=union
*.vbproj merge=union
*.fsproj merge=union
*.dbproj merge=union
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain

View File

@ -1,47 +0,0 @@
# Compiled Object files
*.slo
*.lo
*.o
*.obj
# Precompiled Headers
*.gch
*.pch
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Fortran module files
*.mod
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Executables
*.exe
*.out
*.app
# Buck
/buck-out/
/.buckd/
/buckaroo/
.buckconfig.local
BUCKAROO_DEPS
# Build folder
/build/
# CodeBlocks IDE files
*.layout
# Visual Studio Code
/.vscode/
# Visual Studio
/.vs/

View File

@ -1,4 +0,0 @@
[bugtraq]
url = https://github.com/martinmoene/optional-lite/issues/%BUGID%
number = true
logregex = "(\\s*(,|and)?\\s*#\\d+)+\n(\\d+)"

View File

@ -1,161 +0,0 @@
os: linux
dist: trusty
sudo: false
group: travis_latest
language: c++
cache: ccache
addons:
apt:
sources: &apt_sources
- ubuntu-toolchain-r-test
- llvm-toolchain-precise-3.5
- llvm-toolchain-precise-3.6
- llvm-toolchain-precise-3.7
- llvm-toolchain-precise-3.8
- llvm-toolchain-trusty-3.9
- llvm-toolchain-trusty-4.0
- llvm-toolchain-trusty-5.0
- llvm-toolchain-trusty-6.0
matrix:
include:
- os: linux
env: COMPILER=g++-4.8
compiler: gcc
addons: &gcc4_8
apt:
packages: ["g++-4.8", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=g++-4.9
compiler: gcc
addons: &gcc4_9
apt:
packages: ["g++-4.9", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=g++-5
compiler: gcc
addons: &gcc5
apt:
packages: ["g++-5", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=g++-6
compiler: gcc
addons: &gcc6
apt:
packages: ["g++-6", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=g++-7
compiler: gcc
addons: &gcc7
apt:
packages: ["g++-7", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=g++-8
compiler: gcc
addons: &gcc8
apt:
packages: ["g++-8", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=clang++-3.5
compiler: clang
addons: &clang3_5
apt:
packages: ["clang-3.5", "g++-7", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=clang++-3.6
compiler: clang
addons: &clang3_6
apt:
packages: ["clang-3.6", "g++-7", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=clang++-3.7
compiler: clang
addons: &clang3-7
apt:
packages: ["clang-3.7", "g++-7", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=clang++-3.8
compiler: clang
addons: &clang3_8
apt:
packages: ["clang-3.8", "g++-7", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=clang++-3.9
compiler: clang
addons: &clang3_9
apt:
packages: ["clang-3.9", "g++-7", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=clang++-4.0
compiler: clang
addons: &clang4_0
apt:
packages: ["clang-4.0", "g++-7", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=clang++-5.0
compiler: clang
addons: &clang5_0
apt:
packages: ["clang-5.0", "g++-7", "python3-pip", "lcov"]
sources: *apt_sources
- os: linux
env: COMPILER=clang++-6.0
compiler: clang
addons: &clang6_0
apt:
packages: ["clang-6.0", "g++-7", "python3-pip", "lcov"]
sources: *apt_sources
- os: osx
osx_image: xcode7.3
compiler: clang
env: COMPILER='clang++'
- os: osx
osx_image: xcode8
compiler: clang
env: COMPILER='clang++'
- os: osx
osx_image: xcode9
compiler: clang
env: COMPILER='clang++'
- os: osx
osx_image: xcode10
compiler: clang
env: COMPILER='clang++'
script:
- export CXX=${COMPILER}
- JOBS=2 # Travis machines have 2 cores.
- mkdir build && cd build
- cmake -G "Unix Makefiles" -DOPTIONAL_LITE_OPT_SELECT_NONSTD=ON -DOPTIONAL_LITE_OPT_BUILD_TESTS=ON -DOPTIONAL_LITE_OPT_BUILD_EXAMPLES=OFF ..
- cmake --build . -- -j${JOBS}
- ctest --output-on-failure -j${JOBS}

View File

@ -1,11 +0,0 @@
prebuilt_cxx_library(
name = 'optional-lite',
header_namespace = '',
header_only = True,
exported_headers = subdir_glob([
('include/nonstd', '**/*.hpp'),
]),
visibility = [
'PUBLIC',
],
)

View File

@ -1,13 +0,0 @@
Changes for Optional Lite A single-file header-only [type-safe C++17-like any, a] type-safe container for single values of any type for C++98, C++11 and later
1.0.2 - 2015-04-14
- This release fixes the declaration of nullopt and updates lest_cpp03.hpp to version 1.22.0.
1.0.1 - 2014-12-23
- This release contains several small changes and corrections.
1.0.0 - 2014-12-21
- This is the initial release of optional lite.

View File

@ -1,129 +0,0 @@
# Copyright 2016-2018 by Martin Moene
#
# https://github.com/martinmoene/optional-lite
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
cmake_minimum_required( VERSION 3.5 FATAL_ERROR )
# optional-lite project and version, updated by script/update-version.py:
project(
optional_lite
VERSION 3.4.0
# DESCRIPTION "A C++17-like optional, a nullable object for C++98, C++11 and later in a single-file header-only library"
# HOMEPAGE_URL "https://github.com/martinmoene/optional-lite"
LANGUAGES CXX )
# Package information:
set( unit_name "optional" )
set( package_nspace "nonstd" )
set( package_name "${unit_name}-lite" )
set( package_version "${${PROJECT_NAME}_VERSION}" )
message( STATUS "Project '${PROJECT_NAME}', package '${package_name}' version: '${package_version}'")
# Toplevel or subproject:
if ( CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME )
set( optional_IS_TOPLEVEL_PROJECT TRUE )
else()
set( optional_IS_TOPLEVEL_PROJECT FALSE )
endif()
# If toplevel project, enable building and performing of tests, disable building of examples:
option( OPTIONAL_LITE_OPT_BUILD_TESTS "Build and perform optional-lite tests" ${optional_IS_TOPLEVEL_PROJECT} )
option( OPTIONAL_LITE_OPT_BUILD_EXAMPLES "Build optional-lite examples" OFF )
option( OPTIONAL_LITE_OPT_SELECT_STD "Select std::optional" OFF )
option( OPTIONAL_LITE_OPT_SELECT_NONSTD "Select nonstd::optional" OFF )
# If requested, build and perform tests, build examples:
if ( OPTIONAL_LITE_OPT_BUILD_TESTS )
enable_testing()
add_subdirectory( test )
endif()
if ( OPTIONAL_LITE_OPT_BUILD_EXAMPLES )
add_subdirectory( example )
endif()
#
# Interface, installation and packaging
#
# CMake helpers:
include( GNUInstallDirs )
include( CMakePackageConfigHelpers )
# Interface library:
add_library(
${package_name} INTERFACE )
add_library(
${package_nspace}::${package_name} ALIAS ${package_name} )
target_include_directories(
${package_name}
INTERFACE
"$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>"
"$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>" )
# Package configuration:
# Note: package_name and package_target are used in package_config_in
set( package_folder "${package_name}" )
set( package_target "${package_name}-targets" )
set( package_config "${package_name}-config.cmake" )
set( package_config_in "${package_name}-config.cmake.in" )
set( package_config_version "${package_name}-config-version.cmake" )
configure_package_config_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/${package_config_in}"
"${CMAKE_CURRENT_BINARY_DIR}/${package_config}"
INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${package_folder}"
)
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/${package_config_version}.in"
"${CMAKE_CURRENT_BINARY_DIR}/${package_config_version}" @ONLY
)
# Installation:
install(
TARGETS ${package_name}
EXPORT ${package_target}
# INCLUDES DESTINATION "${...}" # already set via target_include_directories()
)
install(
EXPORT ${package_target}
NAMESPACE ${package_nspace}::
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${package_folder}"
)
install(
FILES "${CMAKE_CURRENT_BINARY_DIR}/${package_config}"
"${CMAKE_CURRENT_BINARY_DIR}/${package_config_version}"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${package_folder}"
)
install(
DIRECTORY "include/"
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
)
export(
EXPORT ${package_target}
NAMESPACE ${package_nspace}::
FILE "${CMAKE_CURRENT_BINARY_DIR}/${package_name}-targets.cmake"
)
# end of file

View File

@ -1,23 +0,0 @@
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.

View File

@ -1,480 +0,0 @@
# optional lite: A single-file header-only version of a C++17-like optional, a nullable object for C++98, C++11 and later
[![Language](https://img.shields.io/badge/C%2B%2B-98/11-blue.svg)](https://en.wikipedia.org/wiki/C%2B%2B#Standardization) [![License](https://img.shields.io/badge/license-BSL-blue.svg)](https://opensource.org/licenses/BSL-1.0) [![Build Status](https://travis-ci.org/martinmoene/optional-lite.svg?branch=master)](https://travis-ci.org/martinmoene/optional-lite) [![Build status](https://ci.appveyor.com/api/projects/status/1oq5gjm7bufrv6ib?svg=true)](https://ci.appveyor.com/project/martinmoene/optional-lite) [![Version](https://badge.fury.io/gh/martinmoene%2Foptional-lite.svg)](https://github.com/martinmoene/optional-lite/releases) [![download](https://img.shields.io/badge/latest-download-blue.svg)](https://raw.githubusercontent.com/martinmoene/optional-lite/master/include/nonstd/optional.hpp) [![Conan](https://img.shields.io/badge/on-conan-blue.svg)](https://conan.io/center/optional-lite) [![Try it online](https://img.shields.io/badge/on-wandbox-blue.svg)](https://wandbox.org/permlink/bfZdDT4WerPNZi6b) [![Try it on godbolt online](https://img.shields.io/badge/on-godbolt-blue.svg)](https://godbolt.org/z/3tecRa)
**Contents**
- [Example usage](#example-usage)
- [In a nutshell](#in-a-nutshell)
- [License](#license)
- [Dependencies](#dependencies)
- [Installation](#installation)
- [Synopsis](#synopsis)
- [Comparison of std::optional, optional lite and Boost.Optional](#comparison-of-stdoptional-optional-lite-and-boostoptional)
- [Reported to work with](#reported-to-work-with)
- [Building the tests](#building-the-tests)
- [Implementation notes](#implementation-notes)
- [Other implementations of optional](#other-implementations-of-optional)
- [Notes and references](#notes-and-references)
- [Appendix](#appendix)
Example usage
-------------
```Cpp
#include "nonstd/optional.hpp"
#include <cstdlib>
#include <iostream>
using nonstd::optional;
using nonstd::nullopt;
optional<int> to_int( char const * const text )
{
char * pos = NULL;
const int value = strtol( text, &pos, 0 );
return pos == text ? nullopt : optional<int>( value );
}
int main( int argc, char * argv[] )
{
char const * text = argc > 1 ? argv[1] : "42";
optional<int> oi = to_int( text );
if ( oi ) std::cout << "'" << text << "' is " << *oi;
else std::cout << "'" << text << "' isn't a number";
}
```
### Compile and run
```
prompt>g++ -Wall -Wextra -std=c++03 -I../include -o 01-to_int.exe 01-to_int.cpp && 01-to_int x1
'x1' isn't a number
```
In a nutshell
---------------
**optional lite** is a single-file header-only library to represent optional (nullable) objects and pass them by value. The library aims to provide a [C++17-like optional](http://en.cppreference.com/w/cpp/utility/optional) for use with C++98 and later. If available, std::optional is used. There's also a simpler version, [*optional bare*](https://github.com/martinmoene/optional-bare). Unlike *optional lite*, *optional bare* is limited to default-constructible and copyable types.
**Features and properties of optional lite** are ease of installation (single header), freedom of dependencies other than the standard library and control over object alignment (if needed). *optional lite* shares the approach to in-place tags with [any-lite](https://github.com/martinmoene/any-lite), [expected-lite](https://github.com/martinmoene/expected-lite) and with [variant-lite](https://github.com/martinmoene/variant-lite) and these libraries can be used together.
**Not provided** are reference-type optionals. *optional lite* doesn't handle overloaded *address of* operators.
For more examples, see [this answer on StackOverflow](http://stackoverflow.com/a/16861022) [8] and the [quick start guide](http://www.boost.org/doc/libs/1_57_0/libs/optional/doc/html/boost_optional/quick_start.html) [9] of Boost.Optional (note that its interface differs from *optional lite*).
License
-------
*optional lite* is distributed under the [Boost Software License](LICENSE.txt).
Dependencies
------------
*optional lite* has no other dependencies than the [C++ standard library](http://en.cppreference.com/w/cpp/header).
Installation
------------
*optional lite* is a single-file header-only library. Put `optional.hpp` in the [include](include) folder directly into the project source tree or somewhere reachable from your project.
Or, if you use the [conan package manager](https://www.conan.io/), you might follow these steps:
1. Create source file `./main.cpp`, e.g. with the contents of the example code above.
2. Create `./conanfile.txt` file with a reference to *variant-lite* in the *requires* section:
```Conan
[requires]
optional-lite/3.2.0 # 3.3.0 when available
[generators]
cmake
```
3. Create `./CMakeLists.txt`:
```CMake
cmake_minimum_required(VERSION 3.1)
project(optional-example CXX)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} ${CONAN_LIBS})
```
4. Run the following commands:
```Text
mkdir build && cd build
conan install .. --settings arch=x86 --settings compiler=gcc
cmake .. -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release
cmake --build . --config Release
```
Synopsis
--------
**Contents**
[Types in namespace nonstd](#types-in-namespace-nonstd)
[Interface of *optional lite*](#interface-of-optional-lite)
[Algorithms for *optional lite*](#algorithms-for-optional-lite)
[Configuration](#configuration)
### Types and values in namespace nonstd
| Purpose | Type / value | Object |
|-----------------------|--------------|--------|
| To be, or not | template< typename T ><br>class **optional**; |&nbsp;|
| Disengaging | struct **nullopt_t**; | nullopt_t nullopt; |
| Error reporting | class **bad_optional_access**; |&nbsp; |
| In-place construction | struct **in_place_tag** | &nbsp; |
| &nbsp; | **in_place** | select type or index for in-place construction |
| &nbsp; | **in_place_type** | select type for in-place construction |
| &emsp;(variant) | **in_place_index** | select index for in-place construction |
| &nbsp; | **nonstd_lite_in_place_type_t**( T) | macro for alias template in_place_type_t&lt;T> |
| &emsp;(variant) | **nonstd_lite_in_place_index_t**( T )| macro for alias template in_place_index_t&lt;T> |
### Interface of *optional lite*
| Kind | Std | Method | Result |
|--------------|------|---------------------------------------------|--------|
| Construction |&nbsp;| **optional**() noexcept | default construct a nulled object |
| &nbsp; |&nbsp;| **optional**( nullopt_t ) noexcept | explicitly construct a nulled object |
| &nbsp; |&nbsp;| **optional**( optional const & rhs ) | move-construct from an other optional |
| &nbsp; | C++11| **optional**( optional && rhs ) noexcept(...) | move-construct from an other optional |
| &nbsp; |&nbsp;| **optional**( value_type const & value ) | copy-construct from a value |
| &nbsp; | C++11| **optional**( value_type && value ) | move-construct from a value |
| &nbsp; | C++11| **explicit optional**( in_place_type_t&lt;T>, Args&&... args ) | in-place-construct type T |
| &nbsp; | C++11| **explicit optional**( in_place_type_t&lt;T>, std::initializer_list&lt;U> il, Args&&... args ) | in-place-construct type T |
| Destruction |&nbsp;| **~optional**() | destruct current content, if any |
| Assignment |&nbsp;| optional & **operator=**( nullopt_t ) | null the object;<br>destruct current content, if any |
| &nbsp; |&nbsp;| optional & **operator=**( optional const & rhs ) | copy-assign from other optional;<br>destruct current content, if any |
| &nbsp; | C++11| optional & **operator=**( optional && rhs ) | move-assign from other optional;<br>destruct current content, if any |
| &nbsp; | C++11| template< class U, ...><br>**optional & operator=( U && v ) | move-assign from a value;<br>destruct current content, if any |
| &nbsp; | C++11| template< class... Args ><br>T & **emplace**( Args&&... args ) | emplace type T |
| &nbsp; | C++11| template< class U, class... Args ><br>T & **emplace**( std::initializer_list&lt;U> il, Args&&... args ) | emplace type T |
| Swap |&nbsp;| void **swap**( optional & rhs ) noexcept(...) | swap with rhs |
| Content |&nbsp;| value_type const \* **operator ->**() const | pointer to current content (const);<br>must contain value |
| &nbsp; |&nbsp;| value_type \* **operator ->**() | pointer to current content (non-const);<br>must contain value |
| &nbsp; |&nbsp;| value_type const & **operator \***() & | the current content (const ref);<br>must contain value |
| &nbsp; |&nbsp;| value_type & **operator \***() & | the current content (non-const ref);<br>must contain value |
| &nbsp; | C++11| value_type const & **operator \***() && | the current content (const ref);<br>must contain value |
| &nbsp; | C++11| value_type & **operator \***() && | the current content (non-const ref);<br>must contain value |
| State |&nbsp;| operator **bool**() const | true if content is present |
| &nbsp; |&nbsp;| bool **has_value**() const | true if content is present |
| &nbsp; |&nbsp;| value_type const & **value**() & | the current content (const ref);<br>throws bad_optional_access if nulled |
| &nbsp; |&nbsp;| value_type & **value**() & | the current content (non-const ref);<br>throws bad_optional_access if nulled |
| &nbsp; | C++11| value_type const & **value**() && | the current content (const ref);<br>throws bad_optional_access if nulled |
| &nbsp; | C++11| value_type & **value**() && | the current content (non-const ref);<br>throws bad_optional_access if nulled |
| &nbsp; |<C++11| value_type **value_or**( value_type const & default_value ) const | the value, or default_value if nulled<br>value_type must be copy-constructible |
| &nbsp; | C++11| value_type **value_or**( value_type && default_value ) & | the value, or default_value if nulled<br>value_type must be copy-constructible |
| &nbsp; | C++11| value_type **value_or**( value_type && default_value ) && | the value, or default_value if nulled<br>value_type must be copy-constructible |
| Modifiers |&nbsp;| void **reset**() noexcept | make empty |
### Algorithms for *optional lite*
| Kind | Std | Function |
|--------------------------|------|----------|
| Relational operators |&nbsp;| &nbsp; |
| == |&nbsp;| template< typename T ><br>bool **operator==**( optional<T> const & x, optional<T> const & y ) |
| != |&nbsp;| template< typename T ><br>bool **operator!=**( optional<T> const & x, optional<T> const & y ) |
| < |&nbsp;| template< typename T ><br>bool **operator<**( optional<T> const & x, optional<T> const & y ) |
| > |&nbsp;| template< typename T ><br>bool **operator>**( optional<T> const & x, optional<T> const & y ) |
| <= |&nbsp;| template< typename T ><br>bool **operator<=*( optional<T> const & x, optional<T> const & y ) |
| >= |&nbsp;| template< typename T ><br>bool **operator>=*( optional<T> const & x, optional<T> const & y ) |
| Comparison with nullopt |&nbsp;| &nbsp; |
| == |&nbsp;| template< typename T ><br>bool **operator==**( optional<T> const & x, nullopt_t ) noexcept |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator==**( nullopt_t, optional<T> const & x ) noexcept |
| != |&nbsp;| template< typename T ><br>bool **operator!=**( optional<T> const & x, nullopt_t ) noexcept |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator!=**( nullopt_t, optional<T> const & x ) noexcept |
| < |&nbsp;| template< typename T ><br>bool **operator<**( optional<T> const &, nullopt_t ) noexcept |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator<**( nullopt_t, optional<T> const & x ) noexcept |
| <= |&nbsp;| template< typename T ><br>bool **operator<=**( optional<T> const & x, nullopt_t ) noexcept |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator<=**( nullopt_t, optional<T> const & ) noexcept |
| > |&nbsp;| template< typename T ><br>bool **operator>**( optional<T> const & x, nullopt_t ) noexcept |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator>**( nullopt_t, optional<T> const & ) noexcept |
| >= |&nbsp;| template< typename T ><br>bool **operator>=**( optional<T> const &, nullopt_t ) noexcept |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator>=**( nullopt_t, optional<T> const & x ) noexcept |
| Comparison with T |&nbsp;| &nbsp; |
| == |&nbsp;| template< typename T ><br>bool **operator==**( optional<T> const & x, const T& v ) |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator==**( T const & v, optional<T> const & x ) |
| != |&nbsp;| template< typename T ><br>bool **operator!=**( optional<T> const & x, const T& v ) |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator!=**( T const & v, optional<T> const & x ) |
| < |&nbsp;| template< typename T ><br>bool **operator<**( optional<T> const & x, const T& v ) |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator<**( T const & v, optional<T> const & x ) |
| <= |&nbsp;| template< typename T ><br>bool **operator<=**( optional<T> const & x, const T& v ) |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator<=**( T const & v, optional<T> const & x ) |
| > |&nbsp;| template< typename T ><br>bool **operator>**( optional<T> const & x, const T& v ) |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator>**( T const & v, optional<T> const & x ) |
| >= |&nbsp;| template< typename T ><br>bool **operator>=**( optional<T> const & x, const T& v ) |
| &nbsp; |&nbsp;| template< typename T ><br>bool **operator>=**( T const & v, optional<T> const & x ) |
| Specialized algorithms |&nbsp;| &nbsp; |
| swap |&nbsp;| template< typename T ><br>void **swap**( optional<T> & x, optional<T> & y ) noexcept(...) |
| create |<C++11| template< typename T ><br>optional&lt;T> **make_optional**( T const & v ) |
| &nbsp; | C++11| template< class T ><br>optional< typename std::decay&lt;T>::type > **make_optional**( T && v ) |
| &nbsp; | C++11| template< class T, class...Args ><br>optional&lt;T> **make_optional**( Args&&... args ) |
| &nbsp; | C++11| template< class T, class U, class... Args ><br>optional&lt;T> **make_optional**( std::initializer_list&lt;U> il, Args&&... args ) |
| hash | C++11| template< class T ><br>class **hash**< nonstd::optional&lt;T> > |
### Configuration
#### Tweak header
If the compiler supports [`__has_include()`](https://en.cppreference.com/w/cpp/preprocessor/include), *optional lite* supports the [tweak header](https://vector-of-bool.github.io/2020/10/04/lib-configuration.html) mechanism. Provide your *tweak header* as `nonstd/optional.tweak.hpp` in a folder in the include-search-path. In the tweak header, provide definitions as documented below, like `#define optional_CPLUSPLUS 201103L`.
#### Standard selection macro
\-D<b>optional\_CPLUSPLUS</b>=199711L
Define this macro to override the auto-detection of the supported C++ standard, if your compiler does not set the `__cplusplus` macro correctly.
#### Select `std::optional` or `nonstd::optional`
At default, *optional lite* uses `std::optional` if it is available and lets you use it via namespace `nonstd`. You can however override this default and explicitly request to use `std::optional` or optional lite's `nonstd::optional` as `nonstd::optional` via the following macros.
-D<b>optional\_CONFIG\_SELECT\_OPTIONAL</b>=optional_OPTIONAL_DEFAULT
Define this to `optional_OPTIONAL_STD` to select `std::optional` as `nonstd::optional`. Define this to `optional_OPTIONAL_NONSTD` to select `nonstd::optional` as `nonstd::optional`. Default is undefined, which has the same effect as defining to `optional_OPTIONAL_DEFAULT`.
#### Disable exceptions
-D<b>optional_CONFIG_NO_EXCEPTIONS</b>=0
Define this to 1 if you want to compile without exceptions. If not defined, the header tries and detect if exceptions have been disabled (e.g. via `-fno-exceptions`). Default is undefined.
#### Macros to control alignment
If *optional lite* is compiled as C++11 or later, C++11 alignment facilities are used for storage of the underlying object. When compiled as pre-C++11, *optional lite* tries to determine proper alignment itself. If this doesn't work out, you can control alignment via the following macros. See also section [Implementation notes](#implementation-notes).
-D<b>optional_CONFIG_MAX_ALIGN_HACK</b>=0
Define this to 1 to use the *max align hack* for alignment. Default is 0.
-D<b>optional_CONFIG_ALIGN_AS</b>=*pod-type*
Define this to the *pod-type* you want to align to (no default).
-D<b>optional_CONFIG_ALIGN_AS_FALLBACK</b>=*pod-type*
Define this to the *pod-type* to use for alignment if the algorithm of *optional lite* cannot find a suitable POD type to use for alignment. Default is double.
Comparison of std::optional, optional lite and Boost.Optional
-------------------------------------------------------------
*optional lite* is inspired on std::optional, which in turn is inspired on Boost.Optional. Here are the significant differences.
| Aspect | std::optional | optional lite | Boost.Optional |
|-----------------------------------|-----------------------|----------------------|----------------|
| Move semantics | yes | C++11 | no |
| noexcept | yes | C++11 | no |
| Hash support | yes | C++11 | no |
| Throwing value accessor | yes | yes | no |
| Literal type | partially | C++11/14 | no |
| In-place construction | emplace, tag in_place | emplace, tag in_place| utility in_place_factory |
| Disengaged state tag | nullopt | nullopt | none |
| optional references | no | no | yes |
| Conversion from optional&lt;U\><br>to optional&lt;T\> | no | no | yes |
| Duplicated interface functions 1) | no | no | yes |
| Explicit convert to ptr (get_ptr) | no | no | yes |
1) is_initialized(), reset(), get().
Reported to work with
---------------------
The table below mentions the compiler versions *optional lite* is reported to work with.
OS | Compiler | Versions |
---------:|:-----------|:---------|
Windows | Clang/LLVM | ? |
&nbsp; | GCC | 5.2.0 |
&nbsp; | Visual C++<br>(Visual Studio)| 8 (2005), 10 (2010), 11 (2012),<br>12 (2013), 14 (2015), 14 (2017) |
GNU/Linux | Clang/LLVM | 3.5.0, 3.6.0, 7.0.0 |
&nbsp; | GCC | 4.8.4, 5, 6, 8 |
&nbsp; | ICC | 19 |
macOS | Xcode | 8.3, 9, 10, 11 |
Building the tests
------------------
To build the tests you need:
- [CMake](http://cmake.org), version 2.8.12 or later to be installed and in your PATH.
- A [suitable compiler](#reported-to-work-with).
The [*lest* test framework](https://github.com/martinmoene/lest) is included in the [test folder](test).
The following steps assume that the [*optional lite* source code](https://github.com/martinmoene/optional-lite) has been cloned into a directory named `c:\optional-lite`.
1. Create a directory for the build outputs for a particular architecture.
Here we use c:\optional-lite\build-win-x86-vc10.
cd c:\optional-lite
md build-win-x86-vc10
cd build-win-x86-vc10
2. Configure CMake to use the compiler of your choice (run `cmake --help` for a list).
cmake -G "Visual Studio 10 2010" -DOPTIONAL_LITE_OPT_BUILD_TESTS=ON ..
3. Build the test suite in the Debug configuration (alternatively use Release).
cmake --build . --config Debug
4. Run the test suite.
ctest -V -C Debug
All tests should pass, indicating your platform is supported and you are ready to use *optional lite*.
Implementation notes
--------------------
### Object allocation and alignment
*optional lite* reserves POD-type storage for an object of the underlying type inside a union to prevent unwanted construction and uses placement new to construct the object when required. Using non-placement new (malloc) to obtain storage, ensures that the memory is properly aligned for the object's type, whereas that's not the case with placement new.
If you access data that's not properly aligned, it 1) may take longer than when it is properly aligned (on x86 processors), or 2) it may terminate the program immediately (many other processors).
Although the C++ standard does not guarantee that all user-defined types have the alignment of some POD type, in practice it's likely they do [8, part 2].
If *optional lite* is compiled as C++11 or later, C++11 alignment facilities are used for storage of the underlying object. When compiling as pre-C++11, *optional lite* tries to determine proper alignment using meta programming. If this doesn't work out, you can control alignment via three macros.
*optional lite* uses the following rules for alignment:
1. If the program compiles as C++11 or later, C++11 alignment facilities are used.
2. If you define -D<b>optional_CONFIG_MAX_ALIGN_HACK</b>=1 the underlying type is aligned as the most restricted type in `struct max_align_t`. This potentially wastes many bytes per optional if the actually required alignment is much less, e.g. 24 bytes used instead of the 2 bytes required.
3. If you define -D<b>optional_CONFIG_ALIGN_AS</b>=*pod-type* the underlying type is aligned as *pod-type*. It's your obligation to specify a type with proper alignment.
4. If you define -D<b>optional_CONFIG_ALIGN_AS_FALLBACK</b>=*pod-type* the fallback type for alignment of rule 5 below becomes *pod-type*. It's your obligation to specify a type with proper alignment.
5. At default, *optional lite* tries to find a POD type with the same alignment as the underlying type.
The algorithm for alignment of 5. is:
- Determine the alignment A of the underlying type using `alignment_of<>`.
- Find a POD type from the list `alignment_types` with exactly alignment A.
- If no such POD type is found, use a type with a relatively strict alignment requirement such as double; this type is specified in `optional_CONFIG_ALIGN_AS_FALLBACK` (default double).
Note that the algorithm of 5. differs from the one Andrei Alexandrescu uses in [8, part 2].
The class template `alignment_of<>` is gleaned from [Boost.TypeTraits, alignment_of](http://www.boost.org/doc/libs/1_57_0/libs/type_traits/doc/html/boost_typetraits/reference/alignment_of.html) [11]. The storage type `storage_t<>` is adapted from the one I created for [spike-expected, expected lite](https://github.com/martinmoene/spike-expected) [13].
For more information on constructed unions and alignment, see [8-12].
Other implementations of optional
---------------------------------
- Isabella Muerte. [MNMLSTC Core](https://github.com/mnmlstc/core) (C++11).
- Andrzej Krzemieński. [optional (nullable) objects for C++14](https://github.com/akrzemi1/Optional). Reference implementation.
- Simon Brand. [C++11/14/17 std::optional with functional-style extensions](https://github.com/TartanLlama/optional).
Notes and references
--------------------
[1] CppReference. [Optional](http://en.cppreference.com/w/cpp/utility/optional).
[2] ISO/IEC WG21. [N4606, section 20.6 Optional objects](http://wg21.link/n4606). July 2016.
[3] Fernando Cacciola, Andrzej Krzemieński. [A proposal to add a utility class to represent optional objects (Revision 5)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3793.html).
[4] Andrzej Krzemieński. [optional (nullable) objects for C++14](https://github.com/akrzemi1/Optional). Reference implementation on GitHub.
[5] Simon Brand. [P0798R0: Monadic operations for std::optional](https://wg21.tartanllama.xyz/monadic-optional).
[6] Simon Brand. [C++11/14/17 std::optional with functional-style extensions ](https://github.com/TartanLlama/optional). Reference implementation on GitHub.
[7] Fernando Cacciola. [Boost.Optional library](http://www.boost.org/doc/libs/1_49_0/libs/optional/doc/html/index.html).
[8] StackOverflow. [How should one use std::optional?](http://stackoverflow.com/a/16861022). Answer by Timothy Shields. 31 May 2013.
[9] Fernando Cacciola. [Boost.Optional Quick start guide](http://www.boost.org/doc/libs/1_57_0/libs/optional/doc/html/boost_optional/quick_start.html).
[10] Andrei Alexandrescu. [Generic<Programming>: Discriminated Unions part 1](http://collaboration.cmc.ec.gc.ca/science/rpn/biblio/ddj/Website/articles/CUJ/2002/cexp2004/alexandr/alexandr.htm), [part 2](http://collaboration.cmc.ec.gc.ca/science/rpn/biblio/ddj/Website/articles/CUJ/2002/cexp2006/alexandr/alexandr.htm), [part 3](http://collaboration.cmc.ec.gc.ca/science/rpn/biblio/ddj/Website/articles/CUJ/2002/cexp2008/alexandr/alexandr.htm). April 2002.
[11] Herb Sutter. [Style Case Study #3: Construction Unions](http://www.gotw.ca/gotw/085.htm). GotW #85. 2009
[12] Kevin T. Manley. [Using Constructed Types in C++ Unions](http://collaboration.cmc.ec.gc.ca/science/rpn/biblio/ddj/Website/articles/CUJ/2002/0208/manley/manley.htm). C/C++ Users Journal, 20(8), August 2002.
[13] StackOverflow. [Determining maximum possible alignment in C++](http://stackoverflow.com/a/3126992).
[14] [Boost.TypeTraits, alignment_of](http://www.boost.org/doc/libs/1_57_0/libs/type_traits/doc/html/boost_typetraits/reference/alignment_of.html) ( [code](http://www.boost.org/doc/libs/1_57_0/boost/type_traits/alignment_of.hpp) ).
[15] Martin Moene. [spike-expected](https://github.com/martinmoene/spike-expected) ([expected-lite.hpp](https://github.com/martinmoene/spike-expected/blob/master/exception_ptr_lite.hpp)).
Appendix
--------
### A.1 Compile-time information
The version of *optional lite* is available via tag `[.version]`. The following tags are available for information on the compiler and on the C++ standard library used: `[.compiler]`, `[.stdc++]`, `[.stdlanguage]` and `[.stdlibrary]`.
### A.2 Optional Lite test specification
```
union: A C++03 union can only contain POD types
optional: Allows to default construct an empty optional (1a)
optional: Allows to explicitly construct a disengaged, empty optional via nullopt (1b)
optional: Allows to default construct an empty optional with a non-default-constructible (1a)
optional: Allows to copy-construct from empty optional (2)
optional: Allows to move-construct from empty optional (C++11, 3)
optional: Allows to copy-construct from empty optional, explicit converting (C++11, 4a)
optional: Allows to copy-construct from empty optional, non-explicit converting (4b)
optional: Allows to move-construct from empty optional, explicit converting (C++11, 5a)
optional: Allows to move-construct from empty optional, non-explicit converting (C++11, 5a)
optional: Allows to copy-construct from non-empty optional (2)
optional: Allows to copy-construct from non-empty optional, explicit converting (C++11, 4a)
optional: Allows to copy-construct from non-empty optional, non-explicit converting (4b)
optional: Allows to move-construct from non-empty optional (C++11, 3)
optional: Allows to move-construct from non-empty optional, explicit converting (C++11, 5a)
optional: Allows to move-construct from non-empty optional, non-explicit converting (C++11, 5b)
optional: Allows to copy-construct from literal value (8)
optional: Allows to copy-construct from literal value, converting (8)
optional: Allows to copy-construct from value (8)
optional: Allows to copy-construct from value, converting (8)
optional: Allows to move-construct from value (C++11, 8b)
optional: Allows to move-construct from value, explicit converting (C++11, 8a)
optional: Allows to move-construct from value, non-explicit converting (C++11, 8b)
optional: Allows to in-place construct from literal value (C++11, 6)
optional: Allows to in-place copy-construct from value (C++11, 6)
optional: Allows to in-place move-construct from value (C++11, 6)
optional: Allows to in-place copy-construct from initializer-list (C++11, 7)
optional: Allows to in-place move-construct from initializer-list (C++11, 7)
optional: Allows to assign nullopt to disengage (1)
optional: Allows to copy-assign from/to engaged and disengaged optionals (2)
optional: Allows to move-assign from/to engaged and disengaged optionals (C++11, 3)
optional: Allows to copy-assign from/to engaged and disengaged optionals, converting, (5)
optional: Allows to move-assign from/to engaged and disengaged optionals, converting (C++11, 6)
optional: Allows to copy-assign from literal value (4)
optional: Allows to copy-assign from value (4)
optional: Allows to move-assign from value (C++11, 4)
optional: Allows to copy-emplace content from arguments (C++11, 7)
optional: Allows to move-emplace content from arguments (C++11, 7)
optional: Allows to copy-emplace content from intializer-list and arguments (C++11, 8)
optional: Allows to move-emplace content from intializer-list and arguments (C++11, 8)
optional: Allows to swap with other optional (member)
optional: Allows to obtain value via operator->()
optional: Allows to obtain moved-value via operator->() (C++11)
optional: Allows to obtain value via operator*()
optional: Allows to obtain moved-value via operator*() (C++11)
optional: Allows to obtain has_value() via operator bool()
optional: Allows to obtain value via value()
optional: Allows to obtain moved-value via value() (C++11)
optional: Allows to obtain value or default via value_or()
optional: Allows to obtain moved-value or moved-default via value_or() (C++11)
optional: Throws bad_optional_access at disengaged access
optional: Throws bad_optional_access with non-empty what()
optional: Allows to reset content
optional: Ensure object is destructed only once (C++11)
optional: Ensure balanced construction-destruction (C++98)
optional: Allows to swaps engage state and values (non-member)
optional: Provides relational operators (non-member)
optional: Provides mixed-type relational operators (non-member)
make_optional: Allows to copy-construct optional
make_optional: Allows to move-construct optional (C++11)
make_optional: Allows to in-place copy-construct optional from arguments (C++11)
make_optional: Allows to in-place move-construct optional from arguments (C++11)
make_optional: Allows to in-place copy-construct optional from initializer-list and arguments (C++11)
make_optional: Allows to in-place move-construct optional from initializer-list and arguments (C++11)
std::hash<>: Allows to obtain hash (C++11)
tweak header: reads tweak header if supported [tweak]
```

View File

@ -1,82 +0,0 @@
version: "{branch} #{build}"
shallow_clone: true
image:
- Visual Studio 2019
- Visual Studio 2017
- Visual Studio 2015
platform:
- Win32
- x64
configuration:
- Debug
- Release
build:
parallel: true
environment:
matrix:
- generator: "Visual Studio 16 2019"
select_sv: -DOPTIONAL_LITE_OPT_SELECT_STD=ON
- generator: "Visual Studio 16 2019"
select_sv: -DOPTIONAL_LITE_OPT_SELECT_NONSTD=ON
- generator: "Visual Studio 15 2017"
select_sv: -DOPTIONAL_LITE_OPT_SELECT_STD=ON
- generator: "Visual Studio 15 2017"
select_sv: -DOPTIONAL_LITE_OPT_SELECT_NONSTD=ON
- generator: "Visual Studio 14 2015"
- generator: "Visual Studio 12 2013"
- generator: "Visual Studio 11 2012"
- generator: "Visual Studio 10 2010"
- generator: "Visual Studio 9 2008"
matrix:
exclude:
- image: Visual Studio 2015
generator: "Visual Studio 16 2019"
- image: Visual Studio 2019
generator: "Visual Studio 15 2017"
- image: Visual Studio 2019
generator: "Visual Studio 14 2015"
- image: Visual Studio 2019
generator: "Visual Studio 12 2013"
- image: Visual Studio 2019
generator: "Visual Studio 11 2012"
- image: Visual Studio 2019
generator: "Visual Studio 10 2010"
- image: Visual Studio 2019
generator: "Visual Studio 9 2008"
- image: Visual Studio 2015
generator: "Visual Studio 15 2017"
- image: Visual Studio 2017
generator: "Visual Studio 16 2019"
- image: Visual Studio 2017
generator: "Visual Studio 14 2015"
- image: Visual Studio 2017
generator: "Visual Studio 12 2013"
- image: Visual Studio 2017
generator: "Visual Studio 11 2012"
- image: Visual Studio 2017
generator: "Visual Studio 10 2010"
- image: Visual Studio 2017
generator: "Visual Studio 9 2008"
- image: Visual Studio 2015
platform: x64
generator: "Visual Studio 9 2008"
- image: Visual Studio 2019
platform: x64
generator: "Visual Studio 9 2008"
before_build:
- mkdir build && cd build
- cmake -A %platform% -G "%generator%" "%select_sv%" -DOPTIONAL_LITE_OPT_BUILD_TESTS=ON -DOPTIONAL_LITE_OPT_BUILD_EXAMPLES=OFF ..
build_script:
- cmake --build . --config %configuration%
test_script:
- ctest --output-on-failure -C %configuration%

View File

@ -1,24 +0,0 @@
# Adapted from write_basic_package_version_file(... COMPATIBILITY SameMajorVersion) output
# ARCH_INDEPENDENT is only present in cmake 3.14 and onwards
set( PACKAGE_VERSION "@package_version@" )
if( PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION )
set( PACKAGE_VERSION_COMPATIBLE FALSE )
else()
if( "@package_version@" MATCHES "^([0-9]+)\\." )
set( CVF_VERSION_MAJOR "${CMAKE_MATCH_1}" )
else()
set( CVF_VERSION_MAJOR "@package_version@" )
endif()
if( PACKAGE_FIND_VERSION_MAJOR STREQUAL CVF_VERSION_MAJOR )
set( PACKAGE_VERSION_COMPATIBLE TRUE )
else()
set( PACKAGE_VERSION_COMPATIBLE FALSE )
endif()
if( PACKAGE_FIND_VERSION STREQUAL PACKAGE_VERSION )
set( PACKAGE_VERSION_EXACT TRUE )
endif()
endif()

View File

@ -1,7 +0,0 @@
@PACKAGE_INIT@
# Only include targets once:
if( NOT TARGET @package_name@::@package_name@ )
include( "${CMAKE_CURRENT_LIST_DIR}/@package_target@.cmake" )
endif()

View File

@ -1,27 +0,0 @@
from conans import ConanFile, CMake
class OptionalLiteConan(ConanFile):
version = "3.4.0"
name = "optional-lite"
description = "A single-file header-only version of a C++17-like optional, a nullable object for C++98, C++11 and later"
license = "Boost Software License - Version 1.0. http://www.boost.org/LICENSE_1_0.txt"
url = "https://github.com/martinmoene/optional-lite.git"
exports_sources = "include/nonstd/*", "CMakeLists.txt", "cmake/*", "LICENSE.txt"
settings = "compiler", "build_type", "arch"
build_policy = "missing"
author = "Martin Moene"
def build(self):
"""Avoid warning on build step"""
pass
def package(self):
"""Run CMake install"""
cmake = CMake(self)
cmake.definitions["OPTIONAL_LITE_OPT_BUILD_TESTS"] = "OFF"
cmake.definitions["OPTIONAL_LITE_OPT_BUILD_EXAMPLES"] = "OFF"
cmake.configure()
cmake.install()
def package_info(self):
self.info.header_only()

View File

@ -1,28 +0,0 @@
#include "nonstd/optional.hpp"
#include <cstdlib>
#include <iostream>
using nonstd::optional;
using nonstd::nullopt;
optional<int> to_int( char const * const text )
{
char * pos = NULL;
const int value = static_cast<int>( strtol( text, &pos, 0 ) );
return pos == text ? nullopt : optional<int>( value );
}
int main( int argc, char * argv[] )
{
const char * text = argc > 1 ? argv[1] : "42";
optional<int> oi = to_int( text );
if ( oi ) std::cout << "'" << text << "' is " << *oi << std::endl;
else std::cout << "'" << text << "' isn't a number" << std::endl;
}
// cl -nologo -W3 -EHsc -I../include to_int.cpp && to_int x1
// g++ -Wall -Wextra -std=c++03 -I../include -o to_int.exe to_int.cpp && to_int x1

View File

@ -1,36 +0,0 @@
#include "nonstd/optional.hpp"
#include <iostream>
#include <vector>
using nonstd::optional;
struct V
{
int v;
V( int v )
: v( v ) {}
};
int main()
{
try
{
int x = 42;
// V s; // V has no default constructor
V t(x); // Ok
std::vector< optional<V> > v(3);
v[0] = t;
std::cout << "v[0].value().v: " << v[0].value().v << "\n";
std::cout << "v[1].value().v: " << v[1].value().v << "\n";
}
catch( std::exception const & e )
{
std::cout << "Error: " << e.what() << "\n";
}
}
// cl -nologo -W3 -EHsc -I../include 00-nodefltctor.cpp && 00-nodefltctor

View File

@ -1,43 +0,0 @@
#include "nonstd/any.hpp"
#include "nonstd/optional.hpp"
#include "nonstd/variant.hpp"
#include <cassert>
#include <string>
using namespace nonstd;
int main()
{
std::string hello = "hello, world";
{
optional< int > var;
assert( ! var );
var = 7 ; assert( *var == 7 );
var = 7 ; assert( var.value() == 7 );
}{
any var;
assert( ! var.has_value() );
var = 'v' ; assert( any_cast<char>( var ) == 'v' );
var = 7 ; assert( any_cast<int >( var ) == 7 );
var = 42L ; assert( any_cast<long>( var ) == 42L );
var = hello; assert( any_cast<std::string>( var ) == hello );
}{
variant< char, int, long, std::string > var;
assert( ! var.valueless_by_exception() );
assert( get< 0 >( var ) == char() );
var = 'v' ; assert( get<char>( var ) == 'v' );
var = 7 ; assert( get<int >( var ) == 7 );
var = 42L ; assert( get<long>( var ) == 42L );
var = hello; assert( get<std::string>( var ) == hello );
}
}
// cl -nologo -EHsc -I../../any-lite/include -I../../optional-lite/include -I../../variant-lite/include 04-any-optional-variant.cpp && 04-any-optional-variant
// g++ -Wall -I../../any-lite/include -I../../optional-lite/include -I../../variant-lite/include -o 04-any-optional-variant 04-any-optional-variant.cpp && 04-any-optional-variant

View File

@ -1,13 +0,0 @@
#include "nonstd/optional.hpp"
using nonstd::optional;
int main()
{
optional<int> v;
v.value(); // asserts (normally throws)
}
// cl -nologo -I../include 05-no-exceptions.cpp && 05-no-exceptions
// g++ -Wall -fno-exceptions -I../include -o 05-no-exceptions 05-no-exceptions.cpp && 05-no-exceptions

View File

@ -1,38 +0,0 @@
cxx_binary(
name = '01-to_int',
srcs = [
'01-to_int.cpp',
],
compiler_flags = [
'-std=c++11',
],
deps = [
'//:optional-lite',
],
)
cxx_binary(
name = '02-nodefltctor',
srcs = [
'02-nodefltctor.cpp',
],
compiler_flags = [
'-std=c++11',
],
deps = [
'//:optional-lite',
],
)
cxx_binary(
name = '04-any-optional-variant',
srcs = [
'04-any-optional-variant.cpp',
],
compiler_flags = [
'-std=c++11',
],
deps = [
'//:optional-lite',
],
)

View File

@ -1,60 +0,0 @@
# Copyright 2017-2018 by Martin Moene
#
# https://github.com/martinmoene/optional-lite
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
if( NOT DEFINED CMAKE_MINIMUM_REQUIRED_VERSION )
cmake_minimum_required( VERSION 3.5 FATAL_ERROR )
endif()
project( example LANGUAGES CXX )
set( unit_name "optional" )
set( PACKAGE ${unit_name}-lite )
set( PROGRAM ${unit_name}-lite )
message( STATUS "Subproject '${PROJECT_NAME}', examples '${PROGRAM}-*'")
set( OPTIONS "" )
if( MSVC )
message( STATUS "Matched: MSVC")
set( BASE_OPTIONS -W3 )
set( EXCEPTIONS_OPTIONS ${BASE_OPTIONS} -EHsc )
set( NO_EXCEPTIONS_OPTIONS ${BASE_OPTIONS} )
elseif( CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|AppleClang" )
message( STATUS "CompilerId: '${CMAKE_CXX_COMPILER_ID}'")
set( BASE_OPTIONS -Wall -Wextra -Wconversion -Wsign-conversion -Wno-missing-braces -fno-elide-constructors )
set( EXCEPTIONS_OPTIONS ${BASE_OPTIONS} )
set( NO_EXCEPTIONS_OPTIONS -fno-exceptions )
elseif( CMAKE_CXX_COMPILER_ID MATCHES "Intel" )
# as is
message( STATUS "Matched: Intel")
else()
# as is
message( STATUS "Matched: nothing")
endif()
function( make_target name no_exceptions )
add_executable ( ${PROGRAM}-${name} ${name}.cpp )
target_link_libraries ( ${PROGRAM}-${name} PRIVATE ${PACKAGE} )
if ( no_exceptions )
target_compile_options ( ${PROGRAM}-${name} PRIVATE ${NO_EXCEPTIONS_OPTIONS} )
else()
target_compile_options ( ${PROGRAM}-${name} PRIVATE ${EXCEPTIONS_OPTIONS} )
endif()
endfunction()
make_target( 01-to_int FALSE )
make_target( 02-nodefltctor FALSE )
# 04-any-optional-variant also requires variant-lite.
make_target( 05-no-exceptions TRUE )
# end of file

View File

@ -1,26 +0,0 @@
# gdb pretty-printer contributed by @bas524, Alexander B.
#
# register with:
# libstdcxx_printer.add_version('nonstd::optional_lite::', 'optional', NonStdOptionalPrinter)
class NonStdOptionalPrinter(SingleObjContainerPrinter):
"Print a nonstd::optional"
def __init__ (self, typename, val):
alternatives = get_template_arg_list(val.type)
valtype = self._recognize (val.type.template_argument(0))
self.typename = strip_versioned_namespace(typename)
self.typename = re.sub('^nonstd::(optional_lite::|)(optional::|)(.*)', r'nonstd::\1\3<%s>' % valtype, self.typename, 1)
self.val = val
self.contained_type = alternatives[0]
addr = val['contained']['data']['__data'].address
contained_value = addr.cast(self.contained_type.pointer()).dereference()
visualizer = gdb.default_visualizer (contained_value)
super (NonStdOptionalPrinter, self).__init__ (contained_value, visualizer)
def to_string (self):
if self.contained_value is None:
return "%s [no contained value]" % self.typename
if self.visualizer:
return "%s containing %s" % (self.typename, self.visualizer.to_string())
return self.typename

File diff suppressed because it is too large Load Diff

View File

@ -1,54 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_project_file>
<FileVersion major="1" minor="6" />
<Project>
<Option title="Optional Lite" />
<Option compiler="gcc" />
<Build>
<Target title="default">
<Option output="any-lite" prefix_auto="1" extension_auto="1" />
<Option type="0" />
<Option compiler="gcc" />
</Target>
</Build>
<Unit filename="../../.gitattributes" />
<Unit filename="../../.gitignore" />
<Unit filename="../../.travis.yml" />
<Unit filename="../../CHANGES.txt" />
<Unit filename="../../CMakeLists.txt" />
<Unit filename="../../LICENSE.txt" />
<Unit filename="../../README.md" />
<Unit filename="../../appveyor.yml" />
<Unit filename="../../cmake/optional-lite-config-version.cmake.in" />
<Unit filename="../../cmake/optional-lite-config.cmake.in" />
<Unit filename="../../conanfile.py" />
<Unit filename="../../example/01-to_int.cpp" />
<Unit filename="../../example/02-nodefltctor.cpp" />
<Unit filename="../../example/04-any-optional-variant.cpp" />
<Unit filename="../../example/05-no-exceptions.cpp" />
<Unit filename="../../example/BUCK" />
<Unit filename="../../extra/gdb/nonstd_optional_printer.py" />
<Unit filename="../../include/nonstd/optional.hpp" />
<Unit filename="../../script/create-cov-rpt.py" />
<Unit filename="../../script/create-vcpkg.py" />
<Unit filename="../../script/update-version.py" />
<Unit filename="../../script/upload-conan.py" />
<Unit filename="../../test/CMakeLists.txt" />
<Unit filename="../../test/Makefile" />
<Unit filename="../../test/lest_cpp03.hpp" />
<Unit filename="../../test/optional-main.t.cpp" />
<Unit filename="../../test/optional-main.t.hpp" />
<Unit filename="../../test/optional.t.cpp" />
<Unit filename="../../test/t.bat" />
<Unit filename="../../test/tc-cl.bat" />
<Unit filename="../../test/tc.bat" />
<Unit filename="../../test/tg-all.bat" />
<Unit filename="../../test/tg.bat" />
<Extensions>
<code_completion />
<envvars />
<debugger />
<lib_finder disable_auto="1" />
</Extensions>
</Project>
</CodeBlocks_project_file>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<CodeBlocks_workspace_file>
<Workspace title="Workspace">
<Project filename="optional-lite.cbp" />
</Workspace>
</CodeBlocks_workspace_file>

View File

@ -1,220 +0,0 @@
#!/usr/bin/env python
#
# Copyright 2019-2019 by Martin Moene
##!/usr/bin/env python
#
# Copyright 2019-2019 by Martin Moene
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
# script/create-cov-rpt.py, Python 3.4 and later
#
import argparse
import os
import re
import sys
import subprocess
# Configuration:
cfg_github_project = 'optional-lite'
cfg_github_user = 'martinmoene'
cfg_prj_folder_level = 3
tpl_coverage_cmd = 'opencppcoverage --no_aggregate_by_file --sources {src} -- {exe}'
# End configuration.
def project_folder( f, args ):
"""Project root"""
if args.prj_folder:
return args.prj_folder
return os.path.normpath( os.path.join( os.path.dirname( os.path.abspath(f) ), '../' * args.prj_folder_level ) )
def executable_folder( f ):
"""Folder where the xecutable is"""
return os.path.dirname( os.path.abspath(f) )
def executable_name( f ):
"""Folder where the executable is"""
return os.path.basename( f )
def createCoverageReport( f, args ):
print( "Creating coverage report for project '{usr}/{prj}', '{file}':".
format( usr=args.user, prj=args.project, file=f ) )
cmd = tpl_coverage_cmd.format( folder=executable_folder(f), src=project_folder(f, args), exe=executable_name(f) )
if args.verbose:
print( "> {}".format(cmd) )
if not args.dry_run:
os.chdir( executable_folder(f) )
subprocess.call( cmd, shell=False )
os.chdir( project_folder(f, args) )
def createCoverageReports( args ):
for f in args.executable:
createCoverageReport( f, args )
def createCoverageReportFromCommandLine():
"""Collect arguments from the commandline and create coverage report."""
parser = argparse.ArgumentParser(
description='Create coverage report.',
epilog="""""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'executable',
metavar='executable',
type=str,
nargs=1,
help='executable to report on')
parser.add_argument(
'-n', '--dry-run',
action='store_true',
help='do not execute conan commands')
parser.add_argument(
'-v', '--verbose',
action='count',
default=0,
help='level of progress reporting')
parser.add_argument(
'--user',
metavar='u',
type=str,
default=cfg_github_user,
help='github user name')
parser.add_argument(
'--project',
metavar='p',
type=str,
default=cfg_github_project,
help='github project name')
parser.add_argument(
'--prj-folder',
metavar='f',
type=str,
default=None,
help='project root folder')
parser.add_argument(
'--prj-folder-level',
metavar='n',
type=int,
default=cfg_prj_folder_level,
help='project root folder level from executable')
createCoverageReports( parser.parse_args() )
if __name__ == '__main__':
createCoverageReportFromCommandLine()
# end of file
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
# script/create-cov-rpt.py, Python 3.4 and later
#
import argparse
import os
import re
import sys
import subprocess
# Configuration:
cfg_github_project = 'expected-lite'
cfg_github_user = 'martinmoene'
tpl_coverage_cmd = 'opencppcoverage --no_aggregate_by_file --sources {src} -- {exe}'
# End configuration.
def project_folder( f, args ):
"""Project root"""
if args.prj_folder:
return args.prj_folder
return os.path.normpath( os.path.join( os.path.dirname( os.path.abspath(f) ), '../../..') )
def executable_folder( f ):
"""Folder where the xecutable is"""
return os.path.dirname( os.path.abspath(f) )
def executable_name( f ):
"""Folder where the executable is"""
return os.path.basename( f )
def createCoverageReport( f, args ):
print( "Creating coverage report for project '{usr}/{prj}', '{file}':".
format( usr=args.user, prj=args.project, file=f ) )
cmd = tpl_coverage_cmd.format( folder=executable_folder(f), src=project_folder(f, args), exe=executable_name(f) )
if args.verbose:
print( "> {}".format(cmd) )
if not args.dry_run:
os.chdir( executable_folder(f) )
subprocess.call( cmd, shell=False )
os.chdir( project_folder(f, args) )
def createCoverageReports( args ):
for f in args.executable:
createCoverageReport( f, args )
def createCoverageReportFromCommandLine():
"""Collect arguments from the commandline and create coverage report."""
parser = argparse.ArgumentParser(
description='Create coverage report.',
epilog="""""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'executable',
metavar='executable',
type=str,
nargs=1,
help='executable to report on')
parser.add_argument(
'-n', '--dry-run',
action='store_true',
help='do not execute conan commands')
parser.add_argument(
'-v', '--verbose',
action='count',
default=0,
help='level of progress reporting')
parser.add_argument(
'--user',
metavar='u',
type=str,
default=cfg_github_user,
help='github user name')
parser.add_argument(
'--project',
metavar='p',
type=str,
default=cfg_github_project,
help='github project name')
parser.add_argument(
'--prj-folder',
metavar='f',
type=str,
default=None,
help='project root folder')
createCoverageReports( parser.parse_args() )
if __name__ == '__main__':
createCoverageReportFromCommandLine()
# end of file

View File

@ -1,223 +0,0 @@
#!/usr/bin/env python
#
# Copyright 2019-2019 by Martin Moene
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
# script/upload-conan.py, Python 3.4 and later
#
import argparse
import os
import re
import sys
import subprocess
# Configuration:
cfg_github_project = 'optional-lite'
cfg_github_user = 'martinmoene'
cfg_description = '(unused)'
cfg_cmakelists = 'CMakeLists.txt'
cfg_readme = 'Readme.md'
cfg_license = 'LICENSE.txt'
cfg_ref_prefix = 'v'
cfg_sha512 = 'dadeda'
cfg_vcpkg_description = '(no description found)'
cfg_vcpkg_root = os.environ['VCPKG_ROOT']
cfg_cmake_optpfx = "OPTIONAL_LITE"
# End configuration.
# vcpkg control and port templates:
tpl_path_vcpkg_control = '{vcpkg}/ports/{prj}/CONTROL'
tpl_path_vcpkg_portfile = '{vcpkg}/ports/{prj}/portfile.cmake'
tpl_vcpkg_control =\
"""Source: {prj}
Version: {ver}
Description: {desc}"""
tpl_vcpkg_portfile =\
"""include(vcpkg_common_functions)
vcpkg_from_github(
OUT_SOURCE_PATH SOURCE_PATH
REPO {usr}/{prj}
REF {ref}
SHA512 {sha}
)
vcpkg_configure_cmake(
SOURCE_PATH ${{SOURCE_PATH}}
PREFER_NINJA
OPTIONS
-D{optpfx}_OPT_BUILD_TESTS=OFF
-D{optpfx}_OPT_BUILD_EXAMPLES=OFF
)
vcpkg_install_cmake()
vcpkg_fixup_cmake_targets(
CONFIG_PATH lib/cmake/${{PORT}}
)
file(REMOVE_RECURSE
${{CURRENT_PACKAGES_DIR}}/debug
${{CURRENT_PACKAGES_DIR}}/lib
)
file(INSTALL
${{SOURCE_PATH}}/{lic} DESTINATION ${{CURRENT_PACKAGES_DIR}}/share/${{PORT}} RENAME copyright
)"""
tpl_vcpkg_note_sha =\
"""
Next actions:
- Obtain package SHA: 'vcpkg install {prj}', copy SHA mentioned in 'Actual hash: [...]'
- Add SHA to package: 'script\create-vcpkg --sha={sha}'
- Install package : 'vcpkg install {prj}'"""
tpl_vcpkg_note_install =\
"""
Next actions:
- Install package: 'vcpkg install {prj}'"""
# End of vcpkg templates
def versionFrom( filename ):
"""Obtain version from CMakeLists.txt"""
with open( filename, 'r' ) as f:
content = f.read()
version = re.search(r'VERSION\s(\d+\.\d+\.\d+)', content).group(1)
return version
def descriptionFrom( filename ):
"""Obtain description from CMakeLists.txt"""
with open( filename, 'r' ) as f:
content = f.read()
description = re.search(r'DESCRIPTION\s"(.*)"', content).group(1)
return description if description else cfg_vcpkg_description
def vcpkgRootFrom( path ):
return path if path else './vcpkg'
def to_ref( version ):
"""Add prefix to version/tag, like v1.2.3"""
return cfg_ref_prefix + version
def control_path( args ):
"""Create path like vcpks/ports/_project_/CONTROL"""
return tpl_path_vcpkg_control.format( vcpkg=args.vcpkg_root, prj=args.project )
def portfile_path( args ):
"""Create path like vcpks/ports/_project_/portfile.cmake"""
return tpl_path_vcpkg_portfile.format( vcpkg=args.vcpkg_root, prj=args.project )
def createControl( args ):
"""Create vcpkg CONTROL file"""
output = tpl_vcpkg_control.format(
prj=args.project, ver=args.version, desc=args.description )
if args.verbose:
print( "Creating control file '{f}':".format( f=control_path( args ) ) )
if args.verbose > 1:
print( output )
os.makedirs( os.path.dirname( control_path( args ) ), exist_ok=True )
with open( control_path( args ), 'w') as f:
print( output, file=f )
def createPortfile( args ):
"""Create vcpkg portfile"""
output = tpl_vcpkg_portfile.format(
optpfx=cfg_cmake_optpfx, usr=args.user, prj=args.project, ref=to_ref(args.version), sha=args.sha, lic=cfg_license )
if args.verbose:
print( "Creating portfile '{f}':".format( f=portfile_path( args ) ) )
if args.verbose > 1:
print( output )
os.makedirs( os.path.dirname( portfile_path( args ) ), exist_ok=True )
with open( portfile_path( args ), 'w') as f:
print( output, file=f )
def printNotes( args ):
if args.sha == cfg_sha512:
print( tpl_vcpkg_note_sha.
format( prj=args.project, sha='...' ) )
else:
print( tpl_vcpkg_note_install.
format( prj=args.project ) )
def createVcpkg( args ):
print( "Creating vcpkg for '{usr}/{prj}', version '{ver}' in folder '{vcpkg}':".
format( usr=args.user, prj=args.project, ver=args.version, vcpkg=args.vcpkg_root, ) )
createControl( args )
createPortfile( args )
printNotes( args )
def createVcpkgFromCommandLine():
"""Collect arguments from the commandline and create vcpkg."""
parser = argparse.ArgumentParser(
description='Create microsoft vcpkg.',
epilog="""""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'-v', '--verbose',
action='count',
default=0,
help='level of progress reporting')
parser.add_argument(
'--user',
metavar='u',
type=str,
default=cfg_github_user,
help='github user name')
parser.add_argument(
'--project',
metavar='p',
type=str,
default=cfg_github_project,
help='github project name')
parser.add_argument(
'--description',
metavar='d',
type=str,
# default=cfg_description,
default=descriptionFrom( cfg_cmakelists ),
help='vcpkg description [from ' + cfg_cmakelists + ']')
parser.add_argument(
'--version',
metavar='v',
type=str,
default=versionFrom( cfg_cmakelists ),
help='version number [from ' + cfg_cmakelists + ']')
parser.add_argument(
'--sha',
metavar='s',
type=str,
default=cfg_sha512,
help='sha of package')
parser.add_argument(
'--vcpkg-root',
metavar='r',
type=str,
default=vcpkgRootFrom( cfg_vcpkg_root ),
help='parent folder containing ports to write files to')
createVcpkg( parser.parse_args() )
if __name__ == '__main__':
createVcpkgFromCommandLine()
# end of file

View File

@ -1,129 +0,0 @@
#!/usr/bin/env python
#
# Copyright 2017-2018 by Martin Moene
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
# script/update-version.py
#
from __future__ import print_function
import argparse
import os
import re
import sys
# Configuration:
table = (
# path, substitute find, substitute format
( 'CMakeLists.txt'
, r'\W{2,4}VERSION\W+([0-9]+\.[0-9]+\.[0-9]+)\W*$'
, ' VERSION {major}.{minor}.{patch}' )
, ( 'CMakeLists.txt'
, r'set\W+optional_lite_version\W+"([0-9]+\.[0-9]+\.[0-9]+)"\W+$'
, 'set( optional_lite_version "{major}.{minor}.{patch}" )\n' )
# , ( 'example/cmake-pkg/CMakeLists.txt'
# , r'set\W+optional_lite_version\W+"([0-9]+\.[0-9]+(\.[0-9]+)?)"\W+$'
# , 'set( optional_lite_version "{major}.{minor}" )\n' )
#
# , ( 'script/install-xxx-pkg.py'
# , r'\optional_lite_version\s+=\s+"([0-9]+\.[0-9]+\.[0-9]+)"\s*$'
# , 'optional_lite_version = "{major}.{minor}.{patch}"\n' )
, ( 'conanfile.py'
, r'version\s+=\s+"([0-9]+\.[0-9]+\.[0-9]+)"\s*$'
, 'version = "{major}.{minor}.{patch}"' )
, ( 'include/nonstd/optional.hpp'
, r'\#define\s+optional_lite_MAJOR\s+[0-9]+\s*$'
, '#define optional_lite_MAJOR {major}' )
, ( 'include/nonstd/optional.hpp'
, r'\#define\s+optional_lite_MINOR\s+[0-9]+\s*$'
, '#define optional_lite_MINOR {minor}' )
, ( 'include/nonstd/optional.hpp'
, r'\#define\s+optional_lite_PATCH\s+[0-9]+\s*$'
, '#define optional_lite_PATCH {patch}\n' )
)
# End configuration.
def readFile( in_path ):
"""Return content of file at given path"""
with open( in_path, 'r' ) as in_file:
contents = in_file.read()
return contents
def writeFile( out_path, contents ):
"""Write contents to file at given path"""
with open( out_path, 'w' ) as out_file:
out_file.write( contents )
def replaceFile( output_path, input_path ):
# prevent race-condition (Python 3.3):
if sys.version_info >= (3, 3):
os.replace( output_path, input_path )
else:
os.remove( input_path )
os.rename( output_path, input_path )
def editFileToVersion( version, info, verbose ):
"""Update version given file path, version regexp and new version format in info"""
major, minor, patch = version.split('.')
in_path, ver_re, ver_fmt = info
out_path = in_path + '.tmp'
new_text = ver_fmt.format( major=major, minor=minor, patch=patch )
if verbose:
print( "- {path} => '{text}':".format( path=in_path, text=new_text.strip('\n') ) )
writeFile(
out_path,
re.sub(
ver_re, new_text, readFile( in_path )
, count=0, flags=re.MULTILINE
)
)
replaceFile( out_path, in_path )
def editFilesToVersion( version, table, verbose ):
if verbose:
print( "Editing files to version {v}:".format(v=version) )
for item in table:
editFileToVersion( version, item, verbose )
def editFilesToVersionFromCommandLine():
"""Update version number given on command line in paths from configuration table."""
parser = argparse.ArgumentParser(
description='Update version number in files.',
epilog="""""",
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
'version',
metavar='version',
type=str,
nargs=1,
help='new version number, like 1.2.3')
parser.add_argument(
'-v', '--verbose',
action='store_true',
help='report the name of the file being processed')
args = parser.parse_args()
editFilesToVersion( args.version[0], table, args.verbose )
if __name__ == '__main__':
editFilesToVersionFromCommandLine()
# end of file

View File

@ -1,114 +0,0 @@
#!/usr/bin/env python
#
# Copyright 2019-2019 by Martin Moene
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
# script/upload-conan.py
#
from __future__ import print_function
import argparse
import os
import re
import sys
import subprocess
# Configuration:
def_conan_project = 'optional-lite'
def_conan_user = 'nonstd-lite'
def_conan_channel = 'stable'
cfg_conanfile = 'conanfile.py'
tpl_conan_create = 'conan create . {usr}/{chn}'
tpl_conan_upload = 'conan upload --remote {usr} {prj}/{ver}@{usr}/{chn}'
# End configuration.
def versionFrom( filename ):
"""Obtain version from conanfile.py"""
with open( filename ) as f:
content = f.read()
version = re.search(r'version\s=\s"(.*)"', content).group(1)
return version
def createConanPackage( args ):
"""Create conan package and upload it."""
cmd = tpl_conan_create.format(usr=args.user, chn=args.channel)
if args.verbose:
print( "> {}".format(cmd) )
if not args.dry_run:
subprocess.call( cmd, shell=False )
def uploadConanPackage( args ):
"""Create conan package and upload it."""
cmd = tpl_conan_upload.format(prj=args.project, usr=args.user, chn=args.channel, ver=args.version)
if args.verbose:
print( "> {}".format(cmd) )
if not args.dry_run:
subprocess.call( cmd, shell=False )
def uploadToConan( args ):
"""Create conan package and upload it."""
print( "Updating project '{prj}' to user '{usr}', channel '{chn}', version {ver}:".
format(prj=args.project, usr=args.user, chn=args.channel, ver=args.version) )
createConanPackage( args )
uploadConanPackage( args )
def uploadToConanFromCommandLine():
"""Collect arguments from the commandline and create conan package and upload it."""
parser = argparse.ArgumentParser(
description='Create conan package and upload it to conan.',
epilog="""""",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument(
'-n', '--dry-run',
action='store_true',
help='do not execute conan commands')
parser.add_argument(
'-v', '--verbose',
action='count',
default=0,
help='level of progress reporting')
parser.add_argument(
'--project',
metavar='p',
type=str,
default=def_conan_project,
help='conan project')
parser.add_argument(
'--user',
metavar='u',
type=str,
default=def_conan_user,
help='conan user')
parser.add_argument(
'--channel',
metavar='c',
type=str,
default=def_conan_channel,
help='conan channel')
parser.add_argument(
'--version',
metavar='v',
type=str,
default=versionFrom( cfg_conanfile ),
help='version number [from conanfile.py]')
uploadToConan( parser.parse_args() )
if __name__ == '__main__':
uploadToConanFromCommandLine()
# end of file

View File

@ -1,16 +0,0 @@
cxx_binary(
name = 'test',
header_namespace = '',
headers = glob([
'*.h',
]),
srcs = glob([
'*.cpp',
]),
compiler_flags = [
'-std=c++11',
],
deps = [
'//:optional-lite',
],
)

View File

@ -1,224 +0,0 @@
# Copyright 2017-2018 by Martin Moene
#
# https://github.com/martinmoene/optional-lite
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
if( NOT DEFINED CMAKE_MINIMUM_REQUIRED_VERSION )
cmake_minimum_required( VERSION 3.5 FATAL_ERROR )
endif()
project( test LANGUAGES CXX )
set( unit_name "optional" )
set( PACKAGE ${unit_name}-lite )
set( PROGRAM ${unit_name}-lite )
set( SOURCES ${unit_name}-main.t.cpp ${unit_name}.t.cpp )
set( TWEAKD "." )
message( STATUS "Subproject '${PROJECT_NAME}', programs '${PROGRAM}-*'")
set( OPTIONS "" )
set( DEFCMN "" )
set( HAS_STD_FLAGS FALSE )
set( HAS_CPP98_FLAG FALSE )
set( HAS_CPP11_FLAG FALSE )
set( HAS_CPP14_FLAG FALSE )
set( HAS_CPP17_FLAG FALSE )
set( HAS_CPP20_FLAG FALSE )
set( HAS_CPPLATEST_FLAG FALSE )
if( MSVC )
message( STATUS "Matched: MSVC")
set( HAS_STD_FLAGS TRUE )
set( OPTIONS -W3 -EHsc )
set( DEFINITIONS -D_SCL_SECURE_NO_WARNINGS ${DEFCMN} )
if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.00 )
set( HAS_CPP14_FLAG TRUE )
set( HAS_CPPLATEST_FLAG TRUE )
endif()
if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.11 )
set( HAS_CPP17_FLAG TRUE )
endif()
elseif( CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang|AppleClang" )
message( STATUS "CompilerId: '${CMAKE_CXX_COMPILER_ID}'")
set( HAS_STD_FLAGS TRUE )
set( HAS_CPP98_FLAG TRUE )
set( OPTIONS -Wall -Wextra -Wconversion -Wsign-conversion -Wno-missing-braces -fno-elide-constructors )
set( DEFINITIONS ${DEFCMN} )
# GNU: available -std flags depends on version
if( CMAKE_CXX_COMPILER_ID MATCHES "GNU" )
message( STATUS "Matched: GNU")
if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.8.0 )
set( HAS_CPP11_FLAG TRUE )
endif()
if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9.2 )
set( HAS_CPP14_FLAG TRUE )
endif()
if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.1.0 )
set( HAS_CPP17_FLAG TRUE )
endif()
# AppleClang: available -std flags depends on version
elseif( CMAKE_CXX_COMPILER_ID MATCHES "AppleClang" )
message( STATUS "Matched: AppleClang")
if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0.0 )
set( HAS_CPP11_FLAG TRUE )
endif()
if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.1.0 )
set( HAS_CPP14_FLAG TRUE )
endif()
if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 9.2.0 )
set( HAS_CPP17_FLAG TRUE )
endif()
# Clang: available -std flags depends on version
elseif( CMAKE_CXX_COMPILER_ID MATCHES "Clang" )
message( STATUS "Matched: Clang")
if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.3.0 )
set( HAS_CPP11_FLAG TRUE )
endif()
if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4.0 )
set( HAS_CPP14_FLAG TRUE )
endif()
if( NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0.0 )
set( HAS_CPP17_FLAG TRUE )
endif()
endif()
elseif( CMAKE_CXX_COMPILER_ID MATCHES "Intel" )
# as is
message( STATUS "Matched: Intel")
else()
# as is
message( STATUS "Matched: nothing")
endif()
# enable MS C++ Core Guidelines checker if MSVC:
function( enable_msvs_guideline_checker target )
if( MSVC )
set_target_properties( ${target} PROPERTIES
VS_GLOBAL_EnableCppCoreCheck true
VS_GLOBAL_CodeAnalysisRuleSet CppCoreCheckRules.ruleset
VS_GLOBAL_RunCodeAnalysis true )
endif()
endfunction()
# make target, compile for given standard if specified:
function( make_target target std )
message( STATUS "Make target: '${std}'" )
add_executable ( ${target} ${SOURCES} )
target_include_directories( ${target} PRIVATE ${TWEAKD} )
target_link_libraries ( ${target} PRIVATE ${PACKAGE} )
target_compile_options ( ${target} PRIVATE ${OPTIONS} )
target_compile_definitions( ${target} PRIVATE ${DEFINITIONS} )
if( std )
if( MSVC )
target_compile_options( ${target} PRIVATE -std:c++${std} )
else()
# Necessary for clang 3.x:
target_compile_options( ${target} PRIVATE -std=c++${std} )
# Ok for clang 4 and later:
# set( CMAKE_CXX_STANDARD ${std} )
# set( CMAKE_CXX_STANDARD_REQUIRED ON )
# set( CMAKE_CXX_EXTENSIONS OFF )
endif()
endif()
endfunction()
# add generic executable, unless -std flags can be specified:
if( NOT HAS_STD_FLAGS )
make_target( ${PROGRAM}.t "" )
else()
# unconditionally add C++98 variant as MSVC has no option for it:
if( HAS_CPP98_FLAG )
make_target( ${PROGRAM}-cpp98.t 98 )
else()
make_target( ${PROGRAM}-cpp98.t "" )
endif()
if( HAS_CPP11_FLAG )
make_target( ${PROGRAM}-cpp11.t 11 )
endif()
if( HAS_CPP14_FLAG )
make_target( ${PROGRAM}-cpp14.t 14 )
endif()
if( HAS_CPP17_FLAG )
set( std17 17 )
if( CMAKE_CXX_COMPILER_ID MATCHES "AppleClang" )
set( std17 1z )
endif()
make_target( ${PROGRAM}-cpp17.t ${std17} )
enable_msvs_guideline_checker( ${PROGRAM}-cpp17.t )
endif()
if( HAS_CPPLATEST_FLAG )
make_target( ${PROGRAM}-cpplatest.t latest )
endif()
endif()
# with C++17, honour explicit request for std::optional or nonstd::optional:
if( HAS_CPP17_FLAG )
set( WHICH optional_OPTIONAL_DEFAULT )
if( OPTIONAL_LITE_OPT_SELECT_STD )
set( WHICH optional_OPTIONAL_STD )
elseif( OPTIONAL_LITE_OPT_SELECT_NONSTD )
set( WHICH optional_OPTIONAL_NONSTD )
endif()
target_compile_definitions( ${PROGRAM}-cpp17.t PRIVATE optional_CONFIG_SELECT_OPTIONAL=${WHICH} )
if( HAS_CPPLATEST_FLAG )
target_compile_definitions( ${PROGRAM}-cpplatest.t PRIVATE optional_CONFIG_SELECT_OPTIONAL=${WHICH} )
endif()
endif()
# configure unit tests via CTest:
enable_testing()
if( HAS_STD_FLAGS )
# unconditionally add C++98 variant for MSVC:
add_test( NAME test-cpp98 COMMAND ${PROGRAM}-cpp98.t )
if( HAS_CPP11_FLAG )
add_test( NAME test-cpp11 COMMAND ${PROGRAM}-cpp11.t )
endif()
if( HAS_CPP14_FLAG )
add_test( NAME test-cpp14 COMMAND ${PROGRAM}-cpp14.t )
endif()
if( HAS_CPP17_FLAG )
add_test( NAME test-cpp17 COMMAND ${PROGRAM}-cpp17.t )
endif()
if( HAS_CPPLATEST_FLAG )
add_test( NAME test-cpplatest COMMAND ${PROGRAM}-cpplatest.t )
endif()
else()
add_test( NAME test COMMAND ${PROGRAM}.t --pass )
add_test( NAME list_version COMMAND ${PROGRAM}.t --version )
add_test( NAME list_tags COMMAND ${PROGRAM}.t --list-tags )
add_test( NAME list_tests COMMAND ${PROGRAM}.t --list-tests )
endif()
# end of file

View File

@ -1,39 +0,0 @@
# Copyright 2014 by Martin Moene
#
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#
# optional lite is inspired on std::optional by Fernando Cacciola and
# Andrzej Krzemienski and on expected lite by Martin Moene.
# Usage: gmake [STD=c++03]
PROGRAM = optional-main.t
SOURCES = $(wildcard *.cpp)
OBJECTS = $(SOURCES:.cpp=.o)
ifdef STD
STD_OPTION = -std=$(STD)
endif
CXX = g++
CXXFLAGS = $(STD_OPTION) -I../include -Wall # -Wextra
all: $(PROGRAM)
$(PROGRAM): $(OBJECTS)
$(CXX) -o $@ $^
test: $(PROGRAM)
./$(PROGRAM)
test-all: $(PROGRAM)
./$(PROGRAM) @
list: test
./$(PROGRAM) -l
clean:
$(RM) $(OBJECTS)
$(RM) $(PROGRAM)

File diff suppressed because it is too large Load Diff

View File

@ -1 +0,0 @@
#define OPTIONAL_TWEAK_VALUE 42

View File

@ -1,116 +0,0 @@
// Copyright (c) 2016 Martin Moene
//
// https://github.com/martinmoene/optional-lite
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include "optional-main.t.hpp"
#ifndef optional_HAVE
# define optional_HAVE(FEATURE) ( optional_HAVE_##FEATURE )
#endif
#define optional_PRESENT( x ) \
std::cout << #x << ": " << x << "\n"
#define optional_ABSENT( x ) \
std::cout << #x << ": (undefined)\n"
lest::tests & specification()
{
static lest::tests tests;
return tests;
}
CASE( "optional-lite version" "[.optional][.version]" )
{
optional_PRESENT( optional_lite_MAJOR );
optional_PRESENT( optional_lite_MINOR );
optional_PRESENT( optional_lite_PATCH );
optional_PRESENT( optional_lite_VERSION );
}
CASE( "optional-lite configuration" "[.optional][.config]" )
{
optional_PRESENT( optional_HAVE_STD_OPTIONAL );
optional_PRESENT( optional_USES_STD_OPTIONAL );
optional_PRESENT( optional_OPTIONAL_DEFAULT );
optional_PRESENT( optional_OPTIONAL_NONSTD );
optional_PRESENT( optional_OPTIONAL_STD );
optional_PRESENT( optional_CONFIG_SELECT_OPTIONAL );
optional_PRESENT( optional_CONFIG_NO_EXCEPTIONS );
optional_PRESENT( optional_CPLUSPLUS );
}
CASE( "__cplusplus" "[.stdc++]" )
{
optional_PRESENT( __cplusplus );
}
CASE( "compiler version" "[.compiler]" )
{
#if optional_USES_STD_OPTIONAL
std::cout << "(Compiler version not available: using std::optional)\n";
#else
optional_PRESENT( optional_COMPILER_CLANG_VERSION );
optional_PRESENT( optional_COMPILER_GNUC_VERSION );
optional_PRESENT( optional_COMPILER_MSVC_VERSION );
#endif
}
CASE( "presence of C++ language features" "[.stdlanguage]" )
{
#if optional_USES_STD_OPTIONAL
std::cout << "(Presence of C++ language features not available: using std::optional)\n";
#else
optional_PRESENT( optional_HAVE_CONSTEXPR_11 );
optional_PRESENT( optional_HAVE_NOEXCEPT );
optional_PRESENT( optional_HAVE_NULLPTR );
optional_PRESENT( optional_HAVE_REF_QUALIFIER );
optional_PRESENT( optional_HAVE_CONSTEXPR_14 );
#endif
}
CASE( "presence of C++ library features" "[.stdlibrary]" )
{
#if optional_USES_STD_OPTIONAL
std::cout << "(Presence of C++ library features not available: using std::optional)\n";
#else
optional_PRESENT( optional_HAVE_CONDITIONAL );
optional_PRESENT( optional_HAVE_REMOVE_CV );
optional_PRESENT( optional_HAVE_TYPE_TRAITS );
optional_PRESENT( optional_HAVE_TR1_TYPE_TRAITS );
optional_PRESENT( optional_HAVE_TR1_ADD_POINTER );
optional_PRESENT( optional_HAVE_IS_ASSIGNABLE );
optional_PRESENT( optional_HAVE_IS_MOVE_CONSTRUCTIBLE );
optional_PRESENT( optional_HAVE_IS_NOTHROW_MOVE_ASSIGNABLE );
optional_PRESENT( optional_HAVE_IS_NOTHROW_MOVE_CONSTRUCTIBLE );
optional_PRESENT( optional_HAVE_IS_TRIVIALLY_COPY_CONSTRUCTIBLE );
optional_PRESENT( optional_HAVE_IS_TRIVIALLY_MOVE_CONSTRUCTIBLE );
#endif
#ifdef _HAS_CPP0X
optional_PRESENT( _HAS_CPP0X );
#else
optional_ABSENT( _HAS_CPP0X );
#endif
}
int main( int argc, char * argv[] )
{
return lest::run( specification(), argc, argv );
}
#if 0
g++ -I../include -o optional-lite.t.exe optional-lite.t.cpp && optional-lite.t.exe --pass
g++ -std=c++98 -I../include -o optional-lite.t.exe optional-lite.t.cpp && optional-lite.t.exe --pass
g++ -std=c++03 -I../include -o optional-lite.t.exe optional-lite.t.cpp && optional-lite.t.exe --pass
g++ -std=c++0x -I../include -o optional-lite.t.exe optional-lite.t.cpp && optional-lite.t.exe --pass
g++ -std=c++11 -I../include -o optional-lite.t.exe optional-lite.t.cpp && optional-lite.t.exe --pass
g++ -std=c++14 -I../include -o optional-lite.t.exe optional-lite.t.cpp && optional-lite.t.exe --pass
g++ -std=c++17 -I../include -o optional-lite.t.exe optional-lite.t.cpp && optional-lite.t.exe --pass
cl -EHsc -I../include optional-lite.t.cpp && optional-lite.t.exe --pass
#endif
// end of file

View File

@ -1,50 +0,0 @@
// Copyright (c) 2016 Martin Moene
//
// https://github.com/martinmoene/optional-lite
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#ifndef TEST_OPTIONAL_LITE_H_INCLUDED
#define TEST_OPTIONAL_LITE_H_INCLUDED
#include "nonstd/optional.hpp"
// Compiler warning suppression for usage of lest:
#ifdef __clang__
# pragma clang diagnostic ignored "-Wstring-conversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wunused-template"
# pragma clang diagnostic ignored "-Wunused-function"
# pragma clang diagnostic ignored "-Wunused-member-function"
#elif defined __GNUC__
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wunused-function"
#endif
#include <iosfwd>
namespace lest { template<typename T> std::ostream & operator<<( std::ostream & os, nonstd::optional<T> const & v ); }
#include "lest_cpp03.hpp"
#define CASE( name ) lest_CASE( specification(), name )
extern lest::tests & specification();
namespace lest {
template< typename T >
inline std::ostream & operator<<( std::ostream & os, nonstd::optional<T> const & v )
{
using lest::to_string;
return os << "[optional:" << (v ? to_string(*v) : "[empty]") << "]";
}
} // namespace lest
#endif // TEST_OPTIONAL_LITE_H_INCLUDED
// end of file

File diff suppressed because it is too large Load Diff

View File

@ -1,56 +0,0 @@
@echo off & setlocal enableextensions enabledelayedexpansion
::
:: t.bat - compile & run tests (MSVC).
::
set unit=optional
:: if no std is given, use compiler default
set std=%1
if not "%std%"=="" set std=-std:%std%
call :CompilerVersion version
echo VC%version%: %args%
set UCAP=%unit%
call :toupper UCAP
set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_DEFAULT
::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_NONSTD
::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_STD
set unit_config=
set msvc_defines=^
-D_CRT_SECURE_NO_WARNINGS ^
-D_SCL_SECURE_NO_WARNINGS
set CppCoreCheckInclude=%VCINSTALLDIR%\Auxiliary\VS\include
cl -W3 -EHsc %std% %unit_select% %unit_config% %msvc_defines% -I../include -I. %unit%-main.t.cpp %unit%.t.cpp && %unit%-main.t.exe
endlocal & goto :EOF
:: subroutines:
:CompilerVersion version
@echo off & setlocal enableextensions
set tmpprogram=_getcompilerversion.tmp
set tmpsource=%tmpprogram%.c
echo #include ^<stdio.h^> >%tmpsource%
echo int main(){printf("%%d\n",_MSC_VER);} >>%tmpsource%
cl /nologo %tmpsource% >nul
for /f %%x in ('%tmpprogram%') do set version=%%x
del %tmpprogram%.* >nul
set offset=0
if %version% LSS 1900 set /a offset=1
set /a version="version / 10 - 10 * ( 5 + offset )"
endlocal & set %1=%version%& goto :EOF
:: toupper; makes use of the fact that string
:: replacement (via SET) is not case sensitive
:toupper
for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L!
goto :EOF

View File

@ -1,6 +0,0 @@
@setlocal
@set std=%1
@if not "%std%"=="" set std=-std:%std%
clang-cl -m32 -W3 -EHsc %std% -Doptional_CONFIG_SELECT_OPTIONAL=optional_OPTIONAL_NONSTD -I../include -I. optional-main.t.cpp optional.t.cpp && optional-main.t.exe
@endlocal

View File

@ -1,53 +0,0 @@
@echo off & setlocal enableextensions enabledelayedexpansion
::
:: tc.bat - compile & run tests (clang).
::
set unit=optional
:: if no std is given, use c++14
set std=%1
if "%std%"=="" set std=c++14
set clang=clang
call :CompilerVersion version
echo %clang% %version%: %std%
set UCAP=%unit%
call :toupper UCAP
set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_DEFAULT
::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_NONSTD
::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_STD
set unit_config=
rem -flto / -fwhole-program
set optflags=-O2
set warnflags=-Wall -Wextra -Wpedantic -Weverything -Wno-c++98-compat -Wno-c++98-compat-pedantic -Wno-padded -Wno-missing-noreturn -Wno-documentation-unknown-command -Wno-documentation-deprecated-sync -Wno-documentation -Wno-weak-vtables -Wno-missing-prototypes -Wno-missing-variable-declarations -Wno-exit-time-destructors -Wno-global-constructors
"%clang%" -m32 -std=%std% %optflags% %warnflags% %unit_select% %unit_config% -fms-compatibility-version=19.00 -isystem "%VCInstallDir%include" -isystem "%WindowsSdkDir_71A%include" -I../include -I. -o %unit%-main.t.exe %unit%-main.t.cpp %unit%.t.cpp && %unit%-main.t.exe
endlocal & goto :EOF
:: subroutines:
:CompilerVersion version
echo off & setlocal enableextensions
set tmpprogram=_getcompilerversion.tmp
set tmpsource=%tmpprogram%.c
echo #include ^<stdio.h^> > %tmpsource%
echo int main(){printf("%%d.%%d.%%d\n",__clang_major__,__clang_minor__,__clang_patchlevel__);} >> %tmpsource%
"%clang%" -m32 -o %tmpprogram% %tmpsource% >nul
for /f %%x in ('%tmpprogram%') do set version=%%x
del %tmpprogram%.* >nul
endlocal & set %1=%version%& goto :EOF
:: toupper; makes use of the fact that string
:: replacement (via SET) is not case sensitive
:toupper
for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L!
goto :EOF

View File

@ -1,3 +0,0 @@
@for %%s in ( c++98 c++03 c++11 c++14 c++17 ) do (
call tg.bat %%s
)

View File

@ -1,55 +0,0 @@
@echo off & setlocal enableextensions enabledelayedexpansion
::
:: tg.bat - compile & run tests (GNUC).
::
set unit=optional
:: if no std is given, use c++11
set std=%1
set args=%2 %3 %4 %5 %6 %7 %8 %9
if "%1" == "" set std=c++11
set gpp=g++
call :CompilerVersion version
echo %gpp% %version%: %std% %args%
set UCAP=%unit%
call :toupper UCAP
set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_DEFAULT
::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_NONSTD
::set unit_select=-D%unit%_CONFIG_SELECT_%UCAP%=%unit%_%UCAP%_STD
set unit_config=
rem -flto / -fwhole-program
set optflags=-O2
set warnflags=-Wall -Wextra -Wpedantic -Wconversion -Wsign-conversion -Wno-padded -Wno-missing-noreturn
%gpp% -std=%std% %optflags% %warnflags% %unit_select% %unit_config% -o %unit%-main.t.exe -I../include -I. %unit%-main.t.cpp %unit%.t.cpp && %unit%-main.t.exe
endlocal & goto :EOF
:: subroutines:
:CompilerVersion version
echo off & setlocal enableextensions
set tmpprogram=_getcompilerversion.tmp
set tmpsource=%tmpprogram%.c
echo #include ^<stdio.h^> > %tmpsource%
echo int main(){printf("%%d.%%d.%%d\n",__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__);} >> %tmpsource%
%gpp% -o %tmpprogram% %tmpsource% >nul
for /f %%x in ('%tmpprogram%') do set version=%%x
del %tmpprogram%.* >nul
endlocal & set %1=%version%& goto :EOF
:: toupper; makes use of the fact that string
:: replacement (via SET) is not case sensitive
:toupper
for %%L IN (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO SET %1=!%1:%%L=%%L!
goto :EOF

View File

@ -3,10 +3,10 @@
#include "icsneo/disk/diskreaddriver.h"
#include "icsneo/disk/diskwritedriver.h"
#include "icsneo/platform/optional.h"
#include "gtest/gtest.h"
#include <queue>
#include <functional>
#include <optional>
using namespace icsneo;
@ -17,7 +17,7 @@ class MockDiskDriver : public Disk::ReadDriver, public Disk::WriteDriver {
public:
std::pair<uint32_t, uint32_t> getBlockSizeBounds() const override { return { 8, 256 }; }
optional<uint64_t> readLogicalDiskAligned(Communication&, device_eventhandler_t,
std::optional<uint64_t> readLogicalDiskAligned(Communication&, device_eventhandler_t,
uint64_t pos, uint8_t* into, uint64_t amount, std::chrono::milliseconds) override {
readCalls++;
@ -26,9 +26,9 @@ public:
EXPECT_EQ(amount % getBlockSizeBounds().first, 0);
if(pos > mockDisk.size()) // EOF
return nullopt;
return std::nullopt;
optional<uint64_t> readAmount = std::min(amount, mockDisk.size() - pos);
std::optional<uint64_t> readAmount = std::min(amount, mockDisk.size() - pos);
if(readAmount > 0u)
memcpy(into, mockDisk.data() + pos, static_cast<size_t>(*readAmount));
@ -39,7 +39,7 @@ public:
return readAmount;
}
optional<uint64_t> writeLogicalDiskAligned(Communication&, device_eventhandler_t report, uint64_t pos,
std::optional<uint64_t> writeLogicalDiskAligned(Communication&, device_eventhandler_t report, uint64_t pos,
const uint8_t* atomicBuf, const uint8_t* from, uint64_t amount, std::chrono::milliseconds) override {
writeCalls++;
@ -48,9 +48,9 @@ public:
EXPECT_EQ(amount % getBlockSizeBounds().first, 0);
if(pos > mockDisk.size()) // EOF
return nullopt;
return std::nullopt;
optional<uint64_t> writeAmount = std::min(amount, mockDisk.size() - pos);
std::optional<uint64_t> writeAmount = std::min(amount, mockDisk.size() - pos);
if(writeAmount > 0u) {
if(atomicBuf) {
if(supportsAtomic) {
@ -107,15 +107,15 @@ protected:
driver.reset();
}
optional<uint64_t> readLogicalDisk(uint64_t pos, uint8_t* into, uint64_t amount) {
std::optional<uint64_t> readLogicalDisk(uint64_t pos, uint8_t* into, uint64_t amount) {
return driver->readLogicalDisk(*com, onError, pos, into, amount /* default timeout */);
}
optional<uint64_t> writeLogicalDisk(uint64_t pos, const uint8_t* from, uint64_t amount) {
std::optional<uint64_t> writeLogicalDisk(uint64_t pos, const uint8_t* from, uint64_t amount) {
return driver->writeLogicalDisk(*com, onError, *driver, pos, from, amount /* default timeout */);
}
optional<MockDiskDriver> driver;
std::optional<MockDiskDriver> driver;
std::queue< std::pair<APIEvent::Type, APIEvent::Severity> > expectedErrors;
device_eventhandler_t onError;

View File

@ -1,6 +1,6 @@
#include "icsneo/communication/ethernetpacketizer.h"
#include "icsneo/platform/optional.h"
#include "gtest/gtest.h"
#include <optional>
using namespace icsneo;
@ -27,7 +27,7 @@ protected:
packetizer.reset();
}
optional<EthernetPacketizer> packetizer;
std::optional<EthernetPacketizer> packetizer;
device_eventhandler_t onError;
};