From a3a7a4e3308afde48e9fe80c17b9168f302cfcfd Mon Sep 17 00:00:00 2001 From: Davide Pesavento Date: Sun, 29 May 2022 16:06:22 -0400 Subject: [PATCH] Use more C++17 features Mainly structured bindings, inline variables, and class template argument deduction, plus many more smaller things. Change-Id: I810d17e0adb470426e4e30c898e03b3140ad052f --- core/common.hpp | 2 + core/network.cpp | 4 +- core/network.hpp | 6 +-- daemon/common/config-file.cpp | 8 +-- daemon/common/privilege-helper.hpp | 4 +- daemon/face/datagram-transport.hpp | 4 +- daemon/face/ethernet-channel.cpp | 14 ++--- daemon/face/ethernet-factory.cpp | 6 +-- daemon/face/ethernet-transport.cpp | 18 +++---- daemon/face/face-common.hpp | 30 ++++++----- daemon/face/face-system.cpp | 13 ++--- daemon/face/face.cpp | 3 +- daemon/face/face.hpp | 2 +- daemon/face/generic-link-service.cpp | 7 +-- daemon/face/generic-link-service.hpp | 4 +- daemon/face/internal-face.cpp | 4 +- daemon/face/lp-fragmenter.cpp | 29 +++++----- daemon/face/lp-reassembler.cpp | 27 ++++------ daemon/face/lp-reassembler.hpp | 17 +++--- daemon/face/lp-reliability.cpp | 18 +++---- daemon/face/lp-reliability.hpp | 26 ++++----- daemon/face/netdev-bound.cpp | 10 ++-- daemon/face/protocol-factory.hpp | 8 +-- daemon/face/tcp-transport.cpp | 14 ++--- daemon/face/tcp-transport.hpp | 17 +++--- daemon/face/transport.hpp | 25 +++++---- daemon/fw/access-strategy.cpp | 18 +++---- daemon/fw/asf-measurements.cpp | 15 ++---- daemon/fw/asf-measurements.hpp | 4 +- daemon/fw/asf-probing-module.cpp | 6 +-- daemon/fw/face-table.cpp | 19 +++---- daemon/fw/forwarder.hpp | 4 +- daemon/fw/retx-suppression-exponential.cpp | 5 +- daemon/fw/retx-suppression-exponential.hpp | 7 ++- daemon/fw/retx-suppression-fixed.cpp | 5 +- daemon/fw/retx-suppression-fixed.hpp | 6 +-- daemon/fw/self-learning-strategy.cpp | 8 +-- daemon/fw/self-learning-strategy.hpp | 5 +- daemon/fw/strategy.hpp | 7 ++- daemon/fw/unsolicited-data-policy.cpp | 13 ++--- daemon/fw/unsolicited-data-policy.hpp | 46 +++++++++------- daemon/mgmt/cs-manager.cpp | 7 +-- daemon/mgmt/face-manager.cpp | 2 +- daemon/mgmt/fib-manager.cpp | 12 ++--- daemon/mgmt/rib-manager.cpp | 8 ++- daemon/mgmt/rib-manager.hpp | 2 +- daemon/mgmt/strategy-choice-manager.cpp | 6 +-- daemon/mgmt/tables-config-section.cpp | 19 +++---- .../host-to-gateway-readvertise-policy.cpp | 4 +- daemon/rib/readvertise/readvertise.cpp | 18 +++---- daemon/rib/readvertise/readvertise.hpp | 14 ++--- daemon/rib/rib-entry.cpp | 14 ++--- daemon/rib/rib-entry.hpp | 20 +++---- daemon/rib/rib-update-batch.hpp | 20 ++++--- daemon/rib/rib-update.cpp | 25 +++------ daemon/rib/rib-update.hpp | 26 ++++----- daemon/rib/rib.cpp | 43 ++++++--------- daemon/rib/rib.hpp | 4 +- daemon/rib/service.cpp | 13 ++--- daemon/rib/service.hpp | 4 +- daemon/table/cs-policy-lru.cpp | 8 ++- daemon/table/cs-policy.cpp | 4 +- daemon/table/cs-policy.hpp | 19 +++---- daemon/table/cs.cpp | 13 ++--- daemon/table/dead-nonce-list.cpp | 17 ++---- daemon/table/fib-entry.cpp | 4 +- daemon/table/fib-entry.hpp | 10 ++-- daemon/table/fib.cpp | 7 +-- daemon/table/fib.hpp | 1 + daemon/table/measurements-entry.hpp | 12 +++-- daemon/table/pit-entry.hpp | 29 +++++----- daemon/table/pit-face-record.cpp | 4 +- daemon/table/pit-iterator.hpp | 4 +- daemon/table/pit.hpp | 4 +- daemon/table/strategy-choice-entry.hpp | 8 +-- tests/core/algorithm.t.cpp | 22 ++++---- tests/core/version.t.cpp | 6 +-- tests/daemon/face/datagram-transport.t.cpp | 2 +- tests/daemon/face/generic-link-service.t.cpp | 53 +++++++++---------- tests/daemon/face/lp-fragmenter.t.cpp | 31 ++++------- tests/daemon/face/lp-reliability.t.cpp | 3 +- tests/daemon/face/tcp-transport.t.cpp | 8 +-- tests/daemon/face/unicast-udp-transport.t.cpp | 4 +- tests/daemon/fw/asf-strategy.t.cpp | 4 +- tests/daemon/fw/strategy-nack-return.t.cpp | 32 ++++------- tests/daemon/fw/strategy-tester.hpp | 4 +- tests/daemon/fw/topology-tester.cpp | 13 ++--- tests/daemon/fw/unsolicited-data-policy.t.cpp | 6 +-- tests/daemon/limited-io.cpp | 5 +- tests/daemon/limited-io.hpp | 6 +-- tests/daemon/mgmt/fib-manager.t.cpp | 3 +- tests/daemon/mgmt/manager-common-fixture.cpp | 2 - tests/daemon/mgmt/manager-common-fixture.hpp | 6 +-- .../daemon/mgmt/rib-manager-sl-announce.t.cpp | 2 +- tests/daemon/mgmt/rib-manager.t.cpp | 3 +- .../daemon/mgmt/strategy-choice-manager.t.cpp | 10 ++-- .../daemon/rib/readvertise/readvertise.t.cpp | 7 ++- tests/daemon/rib/rib-update.t.cpp | 12 ++--- tests/daemon/table/cs.t.cpp | 6 +-- tests/daemon/table/dead-nonce-list.t.cpp | 5 +- tests/daemon/table/fib.t.cpp | 6 +-- tests/daemon/table/name-tree.t.cpp | 45 +++++++--------- tests/daemon/table/pit.t.cpp | 6 +-- tests/daemon/table/strategy-choice.t.cpp | 6 +-- tests/daemon/table/strategy-info-host.t.cpp | 14 ++--- tests/other/face-benchmark.cpp | 30 +++++------ tests/tools/nfdc/command-definition.t.cpp | 3 +- tests/tools/nfdc/execute-command-fixture.hpp | 8 +-- tools/ndn-autoconfig/main.cpp | 6 +-- tools/ndn-autoconfig/multicast-discovery.cpp | 8 +-- tools/ndn-autoconfig/procedure.cpp | 8 +-- tools/nfdc/command-arguments.hpp | 9 ++-- tools/nfdc/command-definition.cpp | 15 +++--- tools/nfdc/command-definition.hpp | 19 +++---- tools/nfdc/command-parser.cpp | 4 +- tools/nfdc/command-parser.hpp | 2 +- tools/nfdc/execute-command.hpp | 18 ++++--- tools/nfdc/find-face.cpp | 5 +- tools/nfdc/format-helpers.cpp | 8 ++- tools/nfdc/format-helpers.hpp | 18 +++---- tools/nfdc/help.cpp | 10 ++-- tools/nfdc/help.hpp | 4 +- tools/nfdc/main.cpp | 16 +++--- tools/nfdc/rib-module.cpp | 4 +- 124 files changed, 621 insertions(+), 799 deletions(-) diff --git a/core/common.hpp b/core/common.hpp index a5f47d9e..96d34a76 100644 --- a/core/common.hpp +++ b/core/common.hpp @@ -54,6 +54,7 @@ #include #include #include +#include #include #include @@ -93,6 +94,7 @@ using std::dynamic_pointer_cast; using std::const_pointer_cast; using namespace std::string_literals; +using namespace std::string_view_literals; using ndn::span; using ndn::to_string; diff --git a/core/network.cpp b/core/network.cpp index eafc3888..bfecec5a 100644 --- a/core/network.cpp +++ b/core/network.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2018, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -59,7 +59,7 @@ Network::getMaxRangeV6() } bool -Network::isValidCidr(const std::string& cidr) +Network::isValidCidr(std::string_view cidr) { auto pos = cidr.find('/'); if (pos == std::string::npos) { diff --git a/core/network.hpp b/core/network.hpp index 1770582c..cc6c2bba 100644 --- a/core/network.hpp +++ b/core/network.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ -/** - * Copyright (c) 2014-2016, Regents of the University of California, +/* + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -51,7 +51,7 @@ public: getMaxRangeV6(); static bool - isValidCidr(const std::string& cidr); + isValidCidr(std::string_view cidr); bool operator==(const Network& rhs) const diff --git a/daemon/common/config-file.cpp b/daemon/common/config-file.cpp index 8d703496..a71badef 100644 --- a/daemon/common/config-file.cpp +++ b/daemon/common/config-file.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -32,8 +32,8 @@ namespace nfd { -ConfigFile::ConfigFile(UnknownConfigSectionHandler unknownSectionCallback) - : m_unknownSectionCallback(unknownSectionCallback) +ConfigFile::ConfigFile(UnknownConfigSectionHandler callback) + : m_unknownSectionCallback(std::move(callback)) { } @@ -77,7 +77,7 @@ void ConfigFile::addSectionHandler(const std::string& sectionName, ConfigSectionHandler subscriber) { - m_subscriptions[sectionName] = subscriber; + m_subscriptions[sectionName] = std::move(subscriber); } void diff --git a/daemon/common/privilege-helper.hpp b/daemon/common/privilege-helper.hpp index f0eb3bd1..b26dce64 100644 --- a/daemon/common/privilege-helper.hpp +++ b/daemon/common/privilege-helper.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -71,7 +71,7 @@ public: { raise(); try { - std::forward(f)(); + std::invoke(std::forward(f)); } catch (...) { drop(); diff --git a/daemon/face/datagram-transport.hpp b/daemon/face/datagram-transport.hpp index e0e2f58f..950a49f2 100644 --- a/daemon/face/datagram-transport.hpp +++ b/daemon/face/datagram-transport.hpp @@ -178,9 +178,7 @@ DatagramTransport::receiveDatagram(span buffer, NFD_LOG_FACE_TRACE("Received: " << buffer.size() << " bytes from " << m_sender); - bool isOk = false; - Block element; - std::tie(isOk, element) = Block::fromBuffer(buffer); + auto [isOk, element] = Block::fromBuffer(buffer); if (!isOk) { NFD_LOG_FACE_WARN("Failed to parse incoming packet from " << m_sender); // This packet won't extend the face lifetime diff --git a/daemon/face/ethernet-channel.cpp b/daemon/face/ethernet-channel.cpp index fae9af2d..2509140a 100644 --- a/daemon/face/ethernet-channel.cpp +++ b/daemon/face/ethernet-channel.cpp @@ -120,19 +120,15 @@ EthernetChannel::handleRead(const boost::system::error_code& error, return; } - span pkt; - std::string err; - std::tie(pkt, err) = m_pcap.readNextPacket(); - + auto [pkt, readErr] = m_pcap.readNextPacket(); if (pkt.empty()) { - NFD_LOG_CHAN_WARN("Read error: " << err); + NFD_LOG_CHAN_WARN("Read error: " << readErr); } else { - const ether_header* eh; - std::tie(eh, err) = ethernet::checkFrameHeader(pkt, m_localEndpoint->getEthernetAddress(), - m_localEndpoint->getEthernetAddress()); + auto [eh, frameErr] = ethernet::checkFrameHeader(pkt, m_localEndpoint->getEthernetAddress(), + m_localEndpoint->getEthernetAddress()); if (eh == nullptr) { - NFD_LOG_CHAN_DEBUG(err); + NFD_LOG_CHAN_DEBUG(frameErr); } else { ethernet::Address sender(eh->ether_shost); diff --git a/daemon/face/ethernet-factory.cpp b/daemon/face/ethernet-factory.cpp index fec671fd..4fea5984 100644 --- a/daemon/face/ethernet-factory.cpp +++ b/daemon/face/ethernet-factory.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2020, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -240,7 +240,7 @@ EthernetFactory::createMulticastFace(const ndn::net::NetworkInterface& netif, { BOOST_ASSERT(address.isMulticast()); - auto key = std::make_pair(netif.getName(), address); + std::pair key(netif.getName(), address); auto found = m_mcastFaces.find(key); if (found != m_mcastFaces.end()) { return found->second; @@ -339,7 +339,7 @@ EthernetFactory::applyMcastConfigToNetif(const ndn::net::NetworkInterface& netif return nullptr; } - if (face->getId() == face::INVALID_FACEID) { + if (face->getId() == INVALID_FACEID) { // new face: register with forwarding this->addFace(face); } diff --git a/daemon/face/ethernet-transport.cpp b/daemon/face/ethernet-transport.cpp index 7aac95af..568064ba 100644 --- a/daemon/face/ethernet-transport.cpp +++ b/daemon/face/ethernet-transport.cpp @@ -168,19 +168,15 @@ EthernetTransport::handleRead(const boost::system::error_code& error) return; } - span pkt; - std::string err; - std::tie(pkt, err) = m_pcap.readNextPacket(); - + auto [pkt, readErr] = m_pcap.readNextPacket(); if (pkt.empty()) { - NFD_LOG_FACE_WARN("Read error: " << err); + NFD_LOG_FACE_WARN("Read error: " << readErr); } else { - const ether_header* eh; - std::tie(eh, err) = ethernet::checkFrameHeader(pkt, m_srcAddress, - m_destAddress.isMulticast() ? m_destAddress : m_srcAddress); + auto [eh, frameErr] = ethernet::checkFrameHeader(pkt, m_srcAddress, + m_destAddress.isMulticast() ? m_destAddress : m_srcAddress); if (eh == nullptr) { - NFD_LOG_FACE_WARN(err); + NFD_LOG_FACE_WARN(frameErr); } else { ethernet::Address sender(eh->ether_shost); @@ -204,9 +200,7 @@ EthernetTransport::receivePayload(span payload, const ethernet::A { NFD_LOG_FACE_TRACE("Received: " << payload.size() << " bytes from " << sender); - bool isOk = false; - Block element; - std::tie(isOk, element) = Block::fromBuffer(payload); + auto [isOk, element] = Block::fromBuffer(payload); if (!isOk) { NFD_LOG_FACE_WARN("Failed to parse incoming packet from " << sender); // This packet won't extend the face lifetime diff --git a/daemon/face/face-common.hpp b/daemon/face/face-common.hpp index 0e6f0bbf..039d2fe3 100644 --- a/daemon/face/face-common.hpp +++ b/daemon/face/face-common.hpp @@ -39,26 +39,28 @@ namespace face { class Face; class LinkService; -/** \brief Identifies a face. +/** + * \brief Identifies a face. */ using FaceId = uint64_t; -/// indicates an invalid FaceId -const FaceId INVALID_FACEID = ndn::nfd::INVALID_FACE_ID; -/// identifies the InternalFace used in management -const FaceId FACEID_INTERNAL_FACE = 1; -/// identifies a packet comes from the ContentStore -const FaceId FACEID_CONTENT_STORE = 254; -/// identifies the NullFace that drops every packet -const FaceId FACEID_NULL = 255; -/// upper bound of reserved FaceIds -const FaceId FACEID_RESERVED_MAX = 255; +/// Indicates an invalid FaceId +constexpr FaceId INVALID_FACEID = ndn::nfd::INVALID_FACE_ID; +/// Identifies the InternalFace used in management +constexpr FaceId FACEID_INTERNAL_FACE = 1; +/// Identifies a packet comes from the ContentStore +constexpr FaceId FACEID_CONTENT_STORE = 254; +/// Identifies the NullFace that drops every packet +constexpr FaceId FACEID_NULL = 255; +/// Upper bound of reserved FaceIds +constexpr FaceId FACEID_RESERVED_MAX = 255; -/** \brief Minimum MTU that may be set +/** + * \brief Minimum MTU that may be set. * - * This is done to ensure the NDNLPv2 fragmentation feature functions properly. + * This is done to ensure the NDNLPv2 fragmentation feature functions properly. */ -const ssize_t MIN_MTU = 64; +constexpr ssize_t MIN_MTU = 64; /** \brief Identifies a remote endpoint on the link. * diff --git a/daemon/face/face-system.cpp b/daemon/face/face-system.cpp index 79cb4365..f86ea25f 100644 --- a/daemon/face/face-system.cpp +++ b/daemon/face/face-system.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -120,22 +120,19 @@ FaceSystem::processConfig(const ConfigSection& configSection, bool isDryRun, con } // process in protocol factories - for (const auto& pair : m_factories) { - const std::string& sectionName = pair.first; - ProtocolFactory* factory = pair.second.get(); - + for (const auto& [sectionName, factory] : m_factories) { std::set oldProvidedSchemes = factory->getProvidedSchemes(); factory->processConfig(configSection.get_child_optional(sectionName), context); if (!isDryRun) { - for (const std::string& scheme : factory->getProvidedSchemes()) { - m_factoryByScheme[scheme] = factory; + for (const auto& scheme : factory->getProvidedSchemes()) { + m_factoryByScheme[scheme] = factory.get(); if (oldProvidedSchemes.erase(scheme) == 0) { NFD_LOG_TRACE("factory " << sectionName << " provides " << scheme << " FaceUri scheme"); } } - for (const std::string& scheme : oldProvidedSchemes) { + for (const auto& scheme : oldProvidedSchemes) { m_factoryByScheme.erase(scheme); NFD_LOG_TRACE("factory " << sectionName << " no longer provides " << scheme << " FaceUri scheme"); diff --git a/daemon/face/face.cpp b/daemon/face/face.cpp index 6422a39c..cc606d0e 100644 --- a/daemon/face/face.cpp +++ b/daemon/face/face.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2017, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -34,7 +34,6 @@ Face::Face(unique_ptr service, unique_ptr transport) , afterReceiveNack(service->afterReceiveNack) , onDroppedInterest(service->onDroppedInterest) , afterStateChange(transport->afterStateChange) - , m_id(INVALID_FACEID) , m_service(std::move(service)) , m_transport(std::move(transport)) , m_counters(m_service->getCounters(), m_transport->getCounters()) diff --git a/daemon/face/face.hpp b/daemon/face/face.hpp index e9731ee3..976a9599 100644 --- a/daemon/face/face.hpp +++ b/daemon/face/face.hpp @@ -202,7 +202,7 @@ public: // properties } private: - FaceId m_id; + FaceId m_id = INVALID_FACEID; unique_ptr m_service; unique_ptr m_transport; FaceCounters m_counters; diff --git a/daemon/face/generic-link-service.cpp b/daemon/face/generic-link-service.cpp index 5ed4ac25..a21aec20 100644 --- a/daemon/face/generic-link-service.cpp +++ b/daemon/face/generic-link-service.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -312,10 +312,7 @@ GenericLinkService::doReceivePacket(const Block& packet, const EndpointId& endpo return; } - bool isReassembled = false; - Block netPkt; - lp::Packet firstPkt; - std::tie(isReassembled, netPkt, firstPkt) = m_reassembler.receiveFragment(endpoint, pkt); + auto [isReassembled, netPkt, firstPkt] = m_reassembler.receiveFragment(endpoint, pkt); if (isReassembled) { this->decodeNetPacket(netPkt, firstPkt, endpoint); } diff --git a/daemon/face/generic-link-service.hpp b/daemon/face/generic-link-service.hpp index 7a86b09d..0f589a3b 100644 --- a/daemon/face/generic-link-service.hpp +++ b/daemon/face/generic-link-service.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -310,7 +310,7 @@ NFD_PUBLIC_WITH_TESTS_ELSE_PRIVATE: /// number of marked packets in the current incident of congestion size_t m_nMarkedSinceInMarkingState; - friend class LpReliability; + friend LpReliability; }; inline const GenericLinkService::Options& diff --git a/daemon/face/internal-face.cpp b/daemon/face/internal-face.cpp index 764dfd7c..a7aa7fb3 100644 --- a/daemon/face/internal-face.cpp +++ b/daemon/face/internal-face.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -46,7 +46,7 @@ makeInternalFace(ndn::KeyChain& clientKeyChain) auto clientFace = make_shared(clientTransport, getGlobalIoService(), clientKeyChain); - return std::make_tuple(face, clientFace); + return {face, clientFace}; } } // namespace face diff --git a/daemon/face/lp-fragmenter.cpp b/daemon/face/lp-fragmenter.cpp index 7494ca7f..6b1755aa 100644 --- a/daemon/face/lp-fragmenter.cpp +++ b/daemon/face/lp-fragmenter.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2018, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -39,18 +39,18 @@ static_assert(lp::tlv::FragIndex < 253, "FragIndex TLV-TYPE must fit in 1 octet" static_assert(lp::tlv::FragCount < 253, "FragCount TLV-TYPE must fit in 1 octet"); static_assert(lp::tlv::Fragment < 253, "Fragment TLV-TYPE must fit in 1 octet"); -/** \brief maximum overhead on a single fragment, - * not counting other NDNLPv2 headers +/** + * \brief Maximum overhead on a single fragment, not counting other NDNLPv2 headers. */ -static const size_t MAX_SINGLE_FRAG_OVERHEAD = +const size_t MAX_SINGLE_FRAG_OVERHEAD = 1 + 9 + // LpPacket TLV-TYPE and TLV-LENGTH 1 + 1 + 8 + // Sequence TLV 1 + 9; // Fragment TLV-TYPE and TLV-LENGTH -/** \brief maximum overhead of adding fragmentation to payload, - * not counting other NDNLPv2 headers +/** + * \brief Maximum overhead of adding fragmentation to payload, not counting other NDNLPv2 headers. */ -static const size_t MAX_FRAG_OVERHEAD = +const size_t MAX_FRAG_OVERHEAD = 1 + 9 + // LpPacket TLV-TYPE and TLV-LENGTH 1 + 1 + 8 + // Sequence TLV 1 + 1 + 8 + // FragIndex TLV @@ -86,18 +86,17 @@ LpFragmenter::fragmentPacket(const lp::Packet& packet, size_t mtu) // fast path: fragmentation not needed // To qualify for fast path, the packet must have space for adding a sequence number, // because another NDNLPv2 feature may require the sequence number. - return std::make_tuple(true, std::vector{packet}); + return {true, {packet}}; } - ndn::Buffer::const_iterator netPktBegin, netPktEnd; - std::tie(netPktBegin, netPktEnd) = packet.get(); + auto [netPktBegin, netPktEnd] = packet.get(); size_t netPktSize = std::distance(netPktBegin, netPktEnd); // compute size of other NDNLPv2 headers to be placed on the first fragment size_t firstHeaderSize = 0; - const Block& packetWire = packet.wireEncode(); + const auto& packetWire = packet.wireEncode(); if (packetWire.type() == lp::tlv::LpPacket) { - for (const Block& element : packetWire.elements()) { + for (const auto& element : packetWire.elements()) { if (element.type() != lp::tlv::Fragment) { firstHeaderSize += element.size(); } @@ -107,7 +106,7 @@ LpFragmenter::fragmentPacket(const lp::Packet& packet, size_t mtu) // compute payload size if (MAX_FRAG_OVERHEAD + firstHeaderSize + 1 > mtu) { // 1-octet fragment NFD_LOG_FACE_WARN("fragmentation error, MTU too small for first fragment: DROP"); - return std::make_tuple(false, std::vector{}); + return {false, {}}; } size_t firstPayloadSize = std::min(netPktSize, mtu - firstHeaderSize - MAX_FRAG_OVERHEAD); size_t payloadSize = mtu - MAX_FRAG_OVERHEAD; @@ -117,7 +116,7 @@ LpFragmenter::fragmentPacket(const lp::Packet& packet, size_t mtu) // compute FragCount if (fragCount > m_options.nMaxFragments) { NFD_LOG_FACE_WARN("fragmentation error, FragCount over limit: DROP"); - return std::make_tuple(false, std::vector{}); + return {false, {}}; } // populate fragments @@ -139,7 +138,7 @@ LpFragmenter::fragmentPacket(const lp::Packet& packet, size_t mtu) } BOOST_ASSERT(fragIndex == fragCount); - return std::make_tuple(true, frags); + return {true, frags}; } std::ostream& diff --git a/daemon/face/lp-reassembler.cpp b/daemon/face/lp-reassembler.cpp index 77a7120a..a4b255ba 100644 --- a/daemon/face/lp-reassembler.cpp +++ b/daemon/face/lp-reassembler.cpp @@ -45,8 +45,6 @@ LpReassembler::receiveFragment(EndpointId remoteEndpoint, const lp::Packet& pack { BOOST_ASSERT(packet.has()); - static auto FALSE_RETURN = std::make_tuple(false, Block(), lp::Packet()); - // read and check FragIndex and FragCount uint64_t fragIndex = 0; uint64_t fragCount = 1; @@ -59,12 +57,12 @@ LpReassembler::receiveFragment(EndpointId remoteEndpoint, const lp::Packet& pack if (fragIndex >= fragCount) { NFD_LOG_FACE_WARN("reassembly error, FragIndex>=FragCount: DROP"); - return FALSE_RETURN; + return {false, {}, {}}; } if (fragCount > m_options.nMaxFragments) { NFD_LOG_FACE_WARN("reassembly error, FragCount over limit: DROP"); - return FALSE_RETURN; + return {false, {}, {}}; } // check for fast path @@ -77,10 +75,11 @@ LpReassembler::receiveFragment(EndpointId remoteEndpoint, const lp::Packet& pack // check Sequence and compute message identifier if (!packet.has()) { NFD_LOG_FACE_WARN("reassembly error, Sequence missing: DROP"); - return FALSE_RETURN; + return {false, {}, {}}; } + lp::Sequence messageIdentifier = packet.get() - fragIndex; - Key key = std::make_tuple(remoteEndpoint, messageIdentifier); + Key key(remoteEndpoint, messageIdentifier); // add to PartialPacket PartialPacket& pp = m_partialPackets[key]; @@ -92,13 +91,13 @@ LpReassembler::receiveFragment(EndpointId remoteEndpoint, const lp::Packet& pack else { if (fragCount != pp.fragCount) { NFD_LOG_FACE_WARN("reassembly error, FragCount changed: DROP"); - return FALSE_RETURN; + return {false, {}, {}}; } } if (pp.fragments[fragIndex].has()) { NFD_LOG_FACE_TRACE("fragment already received: DROP"); - return FALSE_RETURN; + return {false, {}, {}}; } pp.fragments[fragIndex] = packet; @@ -109,13 +108,13 @@ LpReassembler::receiveFragment(EndpointId remoteEndpoint, const lp::Packet& pack Block reassembled = doReassembly(key); lp::Packet firstFrag(std::move(pp.fragments[0])); m_partialPackets.erase(key); - return std::make_tuple(true, reassembled, firstFrag); + return {true, reassembled, firstFrag}; } // set drop timer pp.dropTimer = getScheduler().schedule(m_options.reassemblyTimeout, [=] { timeoutPartialPacket(key); }); - return FALSE_RETURN; + return {false, {}, {}}; } Block @@ -125,20 +124,16 @@ LpReassembler::doReassembly(const Key& key) size_t payloadSize = std::accumulate(pp.fragments.begin(), pp.fragments.end(), 0U, [&] (size_t sum, const lp::Packet& pkt) -> size_t { - ndn::Buffer::const_iterator fragBegin, fragEnd; - std::tie(fragBegin, fragEnd) = pkt.get(); + auto [fragBegin, fragEnd] = pkt.get(); return sum + std::distance(fragBegin, fragEnd); }); ndn::Buffer fragBuffer(payloadSize); auto it = fragBuffer.begin(); - for (const lp::Packet& frag : pp.fragments) { - ndn::Buffer::const_iterator fragBegin, fragEnd; - std::tie(fragBegin, fragEnd) = frag.get(); + auto [fragBegin, fragEnd] = frag.get(); it = std::copy(fragBegin, fragEnd, it); } - return Block(fragBuffer); } diff --git a/daemon/face/lp-reassembler.hpp b/daemon/face/lp-reassembler.hpp index 95c66ff5..59db89b0 100644 --- a/daemon/face/lp-reassembler.hpp +++ b/daemon/face/lp-reassembler.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -33,8 +33,9 @@ namespace nfd { namespace face { -/** \brief reassembles fragmented network-layer packets - * \sa https://redmine.named-data.net/projects/nfd/wiki/NDNLPv2 +/** + * \brief Reassembles fragmented network-layer packets + * \sa https://redmine.named-data.net/projects/nfd/wiki/NDNLPv2 */ class LpReassembler : noncopyable { @@ -96,7 +97,8 @@ public: signal::Signal beforeTimeout; private: - /** \brief holds all fragments of packet until reassembled + /** + * \brief Holds all fragments of packet until reassembled */ struct PartialPacket { @@ -106,12 +108,13 @@ private: scheduler::ScopedEventId dropTimer; }; - /** \brief index key for PartialPackets + /** + * \brief Index key for PartialPackets */ - typedef std::tuple< + using Key = std::tuple< EndpointId, // remoteEndpoint lp::Sequence // message identifier (sequence of the first fragment) - > Key; + >; Block doReassembly(const Key& key); diff --git a/daemon/face/lp-reliability.cpp b/daemon/face/lp-reliability.cpp index 95849b16..b287bc31 100644 --- a/daemon/face/lp-reliability.cpp +++ b/daemon/face/lp-reliability.cpp @@ -80,10 +80,7 @@ LpReliability::handleOutgoing(std::vector& frags, lp::Packet&& pkt, lp::Sequence txSeq = assignTxSequence(frag); // Store LpPacket for future retransmissions - unackedFragsIt = m_unackedFrags.emplace_hint(unackedFragsIt, - std::piecewise_construct, - std::forward_as_tuple(txSeq), - std::forward_as_tuple(frag)); + unackedFragsIt = m_unackedFrags.try_emplace(unackedFragsIt, txSeq, frag); unackedFragsIt->second.sendTime = sendTime; auto rto = m_rttEst.getEstimatedRto(); lp::Sequence seq = frag.get(); @@ -179,7 +176,7 @@ LpReliability::processIncomingPacket(const lp::Packet& pkt) m_recentRecvSeqs.erase(m_recentRecvSeqsQueue.front()); m_recentRecvSeqsQueue.pop(); } - m_recentRecvSeqs.emplace(pktSequence, now); + m_recentRecvSeqs.try_emplace(pktSequence, now); m_recentRecvSeqsQueue.push(pktSequence); } @@ -324,13 +321,10 @@ LpReliability::onLpPacketLost(lp::Sequence txSeq, bool isTimeout) netPkt->didRetx = true; // Move fragment to new TxSequence mapping - auto newTxFragIt = m_unackedFrags.emplace_hint( - m_firstUnackedFrag != m_unackedFrags.end() && m_firstUnackedFrag->first > newTxSeq - ? m_firstUnackedFrag - : m_unackedFrags.end(), - std::piecewise_construct, - std::forward_as_tuple(newTxSeq), - std::forward_as_tuple(txFrag.pkt)); + auto hint = m_firstUnackedFrag != m_unackedFrags.end() && m_firstUnackedFrag->first > newTxSeq + ? m_firstUnackedFrag + : m_unackedFrags.end(); + auto newTxFragIt = m_unackedFrags.try_emplace(hint, newTxSeq, txFrag.pkt); auto& newTxFrag = newTxFragIt->second; newTxFrag.retxCount = txFrag.retxCount + 1; newTxFrag.netPkt = netPkt; diff --git a/daemon/face/lp-reliability.hpp b/daemon/face/lp-reliability.hpp index 4349fca5..c83b0bc0 100644 --- a/daemon/face/lp-reliability.hpp +++ b/daemon/face/lp-reliability.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -39,12 +39,18 @@ namespace face { class GenericLinkService; -/** \brief provides for reliable sending and receiving of link-layer packets - * \sa https://redmine.named-data.net/projects/nfd/wiki/NDNLPv2 +/** + * \brief Provides for reliable sending and receiving of link-layer packets + * \sa https://redmine.named-data.net/projects/nfd/wiki/NDNLPv2 */ class LpReliability : noncopyable { public: + /// TxSequence TLV-TYPE (3 octets) + TLV-LENGTH (1 octet) + lp::Sequence (8 octets) + static constexpr size_t RESERVED_HEADER_SPACE = tlv::sizeOfVarNumber(lp::tlv::TxSequence) + + tlv::sizeOfVarNumber(sizeof(lp::Sequence)) + + sizeof(lp::Sequence); + struct Options { /** \brief enables link-layer reliability @@ -110,7 +116,6 @@ NFD_PUBLIC_WITH_TESTS_ELSE_PRIVATE: class NetPkt; using UnackedFrags = std::map; -NFD_PUBLIC_WITH_TESTS_ELSE_PRIVATE: /** \brief assign TxSequence number to a fragment * \param frag fragment to assign TxSequence to * \return assigned TxSequence number @@ -163,7 +168,8 @@ NFD_PUBLIC_WITH_TESTS_ELSE_PRIVATE: deleteUnackedFrag(UnackedFrags::iterator fragIt); NFD_PUBLIC_WITH_TESTS_ELSE_PRIVATE: - /** \brief contains a sent fragment that has not been acknowledged and associated data + /** + * \brief Contains a sent fragment that has not been acknowledged and associated data */ class UnackedFrag { @@ -180,7 +186,8 @@ NFD_PUBLIC_WITH_TESTS_ELSE_PRIVATE: shared_ptr netPkt; }; - /** \brief contains a network-layer packet with unacknowledged fragments + /** + * \brief Contains a network-layer packet with unacknowledged fragments */ class NetPkt { @@ -194,13 +201,6 @@ NFD_PUBLIC_WITH_TESTS_ELSE_PRIVATE: bool didRetx; }; -public: - /// TxSequence TLV-TYPE (3 octets) + TLV-LENGTH (1 octet) + lp::Sequence (8 octets) - static constexpr size_t RESERVED_HEADER_SPACE = tlv::sizeOfVarNumber(lp::tlv::TxSequence) + - tlv::sizeOfVarNumber(sizeof(lp::Sequence)) + - sizeof(lp::Sequence); - -NFD_PUBLIC_WITH_TESTS_ELSE_PRIVATE: Options m_options; GenericLinkService* m_linkService; UnackedFrags m_unackedFrags; diff --git a/daemon/face/netdev-bound.cpp b/daemon/face/netdev-bound.cpp index 124ea3a7..b22bf627 100644 --- a/daemon/face/netdev-bound.cpp +++ b/daemon/face/netdev-bound.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -46,9 +46,7 @@ NetdevBound::processConfig(OptionalConfigSection configSection, std::vector rules; if (configSection) { int ruleIndex = 0; - for (const auto& pair : *configSection) { - const std::string& key = pair.first; - const ConfigSection& value = pair.second; + for (const auto& [key, value] : *configSection) { if (key == "rule") { rules.push_back(parseRule(ruleIndex++, value)); } @@ -94,9 +92,7 @@ NetdevBound::parseRule(int index, const ConfigSection& confRule) const bool hasWhitelist = false; bool hasBlacklist = false; - for (const auto& pair : confRule) { - const std::string& key = pair.first; - const ConfigSection& value = pair.second; + for (const auto& [key, value] : confRule) { if (key == "remote") { try { rule.remotes.emplace_back(value.get_value()); diff --git a/daemon/face/protocol-factory.hpp b/daemon/face/protocol-factory.hpp index 50023cc0..fcc04188 100644 --- a/daemon/face/protocol-factory.hpp +++ b/daemon/face/protocol-factory.hpp @@ -69,9 +69,11 @@ public: // registry static void registerType(const std::string& id = PF::getId()) { - Registry& registry = getRegistry(); - BOOST_ASSERT(registry.count(id) == 0); - registry[id] = [] (const CtorParams& p) { return make_unique(p); }; + BOOST_ASSERT(!id.empty()); + auto r = getRegistry().insert_or_assign(id, [] (auto&&... p) { + return make_unique(std::forward(p)...); + }); + BOOST_VERIFY(r.second); } /** \brief Create a protocol factory instance diff --git a/daemon/face/tcp-transport.cpp b/daemon/face/tcp-transport.cpp index 0da07af9..466e2c6c 100644 --- a/daemon/face/tcp-transport.cpp +++ b/daemon/face/tcp-transport.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -36,16 +36,12 @@ namespace face { NFD_LOG_MEMBER_INIT_SPECIALIZED(StreamTransport, TcpTransport); -time::milliseconds TcpTransport::s_initialReconnectWait = 1_s; -time::milliseconds TcpTransport::s_maxReconnectWait = 5_min; -float TcpTransport::s_reconnectWaitMultiplier = 2.0f; - TcpTransport::TcpTransport(protocol::socket&& socket, ndn::nfd::FacePersistency persistency, ndn::nfd::FaceScope faceScope) : StreamTransport(std::move(socket)) , m_remoteEndpoint(m_socket.remote_endpoint()) - , m_nextReconnectWait(s_initialReconnectWait) + , m_nextReconnectWait(INITIAL_RECONNECT_DELAY) { this->setLocalUri(FaceUri(m_socket.local_endpoint())); this->setRemoteUri(FaceUri(m_socket.remote_endpoint())); @@ -165,7 +161,7 @@ TcpTransport::handleReconnect(const boost::system::error_code& error) } m_reconnectEvent.cancel(); - m_nextReconnectWait = s_initialReconnectWait; + m_nextReconnectWait = INITIAL_RECONNECT_DELAY; this->setLocalUri(FaceUri(m_socket.local_endpoint())); NFD_LOG_FACE_TRACE("TCP connection reestablished"); @@ -182,8 +178,8 @@ TcpTransport::handleReconnectTimeout() // exponentially back off the reconnection timer m_nextReconnectWait = - std::min(time::duration_cast(m_nextReconnectWait * s_reconnectWaitMultiplier), - s_maxReconnectWait); + std::min(time::duration_cast(m_nextReconnectWait * RECONNECT_DELAY_MULTIPLIER), + MAX_RECONNECT_DELAY); // do this asynchronously because there could be some callbacks still pending getGlobalIoService().post([this] { reconnect(); }); diff --git a/daemon/face/tcp-transport.hpp b/daemon/face/tcp-transport.hpp index c300eedf..950d850d 100644 --- a/daemon/face/tcp-transport.hpp +++ b/daemon/face/tcp-transport.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -72,17 +72,20 @@ NFD_PROTECTED_WITH_TESTS_ELSE_PRIVATE: handleReconnectTimeout(); NFD_PUBLIC_WITH_TESTS_ELSE_PRIVATE: - /** \brief how long to wait before the first reconnection attempt after the TCP connection has been severed + /** + * \brief Delay before the first reconnection attempt after the TCP connection has been severed */ - static time::milliseconds s_initialReconnectWait; + static constexpr time::milliseconds INITIAL_RECONNECT_DELAY = 1_s; - /** \brief maximum amount of time to wait before a reconnection attempt + /** + * \brief Maximum amount of time to wait before a reconnection attempt */ - static time::milliseconds s_maxReconnectWait; + static constexpr time::milliseconds MAX_RECONNECT_DELAY = 5_min; - /** \brief multiplier for the exponential backoff of the reconnection timer + /** + * \brief Multiplier for the exponential backoff of the reconnection timer */ - static float s_reconnectWaitMultiplier; + static constexpr float RECONNECT_DELAY_MULTIPLIER = 2.0f; private: typename protocol::endpoint m_remoteEndpoint; diff --git a/daemon/face/transport.hpp b/daemon/face/transport.hpp index 9b84c99e..2725596f 100644 --- a/daemon/face/transport.hpp +++ b/daemon/face/transport.hpp @@ -86,24 +86,29 @@ public: ByteCounter nOutBytes; }; -/** \brief indicates the transport has no limit on payload size +/** + * \brief Indicates that the transport has no limit on payload size */ -const ssize_t MTU_UNLIMITED = -1; +constexpr ssize_t MTU_UNLIMITED = -1; -/** \brief (for internal use) indicates MTU field is unset +/** + * \brief (for internal use) Indicates that the MTU field is unset */ -const ssize_t MTU_INVALID = -2; +constexpr ssize_t MTU_INVALID = -2; -/** \brief indicates that the transport does not support reading the queue capacity/length +/** + * \brief Indicates that the transport does not support reading the queue capacity/length */ -const ssize_t QUEUE_UNSUPPORTED = -1; +constexpr ssize_t QUEUE_UNSUPPORTED = -1; -/** \brief indicates that the transport was unable to retrieve the queue capacity/length +/** + * \brief Indicates that the transport was unable to retrieve the queue capacity/length */ -const ssize_t QUEUE_ERROR = -2; +constexpr ssize_t QUEUE_ERROR = -2; -/** \brief The lower half of a Face. - * \sa Face +/** + * \brief The lower half of a Face. + * \sa Face */ class Transport : protected virtual TransportCounters, noncopyable { diff --git a/daemon/fw/access-strategy.cpp b/daemon/fw/access-strategy.cpp index e1443df4..e80c5810 100644 --- a/daemon/fw/access-strategy.cpp +++ b/daemon/fw/access-strategy.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -60,8 +60,7 @@ void AccessStrategy::afterReceiveInterest(const Interest& interest, const FaceEndpoint& ingress, const shared_ptr& pitEntry) { - auto suppressResult = m_retxSuppression.decidePerPitEntry(*pitEntry); - switch (suppressResult) { + switch (auto res = m_retxSuppression.decidePerPitEntry(*pitEntry); res) { case RetxSuppressionResult::NEW: return afterReceiveNewInterest(interest, ingress, pitEntry); case RetxSuppressionResult::FORWARD: @@ -77,9 +76,7 @@ AccessStrategy::afterReceiveNewInterest(const Interest& interest, const FaceEndp const shared_ptr& pitEntry) { const auto& fibEntry = this->lookupFib(*pitEntry); - Name miName; - MtInfo* mi = nullptr; - std::tie(miName, mi) = this->findPrefixMeasurements(*pitEntry); + auto [miName, mi] = this->findPrefixMeasurements(*pitEntry); // has measurements for Interest Name? if (mi != nullptr) { @@ -236,10 +233,7 @@ AccessStrategy::beforeSatisfyInterest(const Data& data, const FaceEndpoint& ingr void AccessStrategy::updateMeasurements(const Face& inFace, const Data& data, time::nanoseconds rtt) { - auto ret = m_fit.emplace(std::piecewise_construct, - std::forward_as_tuple(inFace.getId()), - std::forward_as_tuple(m_rttEstimatorOpts)); - FaceInfo& fi = ret.first->second; + FaceInfo& fi = m_fit.try_emplace(inFace.getId(), m_rttEstimatorOpts).first->second; fi.rtt.addMeasurement(rtt); MtInfo* mi = this->addPrefixMeasurements(data); @@ -257,14 +251,14 @@ AccessStrategy::findPrefixMeasurements(const pit::Entry& pitEntry) { auto me = this->getMeasurements().findLongestPrefixMatch(pitEntry); if (me == nullptr) { - return std::make_tuple(Name(), nullptr); + return {Name{}, nullptr}; } auto mi = me->getStrategyInfo(); // TODO: after a runtime strategy change, it's possible that a measurements::Entry exists but // the corresponding MtInfo doesn't exist (mi == nullptr); this case needs another longest // prefix match until an MtInfo is found. - return std::make_tuple(me->getName(), mi); + return {me->getName(), mi}; } AccessStrategy::MtInfo* diff --git a/daemon/fw/asf-measurements.cpp b/daemon/fw/asf-measurements.cpp index 2eb81ddd..c49f5d54 100644 --- a/daemon/fw/asf-measurements.cpp +++ b/daemon/fw/asf-measurements.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -30,9 +30,6 @@ namespace nfd { namespace fw { namespace asf { -const time::nanoseconds FaceInfo::RTT_NO_MEASUREMENT{-1}; -const time::nanoseconds FaceInfo::RTT_TIMEOUT{-2}; - time::nanoseconds FaceInfo::scheduleTimeout(const Name& interestName, scheduler::EventCallback cb) { @@ -63,11 +60,9 @@ NamespaceInfo::getFaceInfo(FaceId faceId) FaceInfo& NamespaceInfo::getOrCreateFaceInfo(FaceId faceId) { - auto ret = m_fiMap.emplace(std::piecewise_construct, - std::forward_as_tuple(faceId), - std::forward_as_tuple(m_rttEstimatorOpts)); - auto& faceInfo = ret.first->second; - if (ret.second) { + auto [it, isNew] = m_fiMap.try_emplace(faceId, m_rttEstimatorOpts); + auto& faceInfo = it->second; + if (isNew) { extendFaceInfoLifetime(faceInfo, faceId); } return faceInfo; @@ -83,8 +78,6 @@ NamespaceInfo::extendFaceInfoLifetime(FaceInfo& info, FaceId faceId) //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// -constexpr time::microseconds AsfMeasurements::MEASUREMENTS_LIFETIME; - AsfMeasurements::AsfMeasurements(MeasurementsAccessor& measurements) : m_measurements(measurements) , m_rttEstimatorOpts(make_shared()) diff --git a/daemon/fw/asf-measurements.hpp b/daemon/fw/asf-measurements.hpp index a3eafc95..1d2b90fc 100644 --- a/daemon/fw/asf-measurements.hpp +++ b/daemon/fw/asf-measurements.hpp @@ -105,8 +105,8 @@ public: } public: - static const time::nanoseconds RTT_NO_MEASUREMENT; - static const time::nanoseconds RTT_TIMEOUT; + static constexpr time::nanoseconds RTT_NO_MEASUREMENT = -1_ns; + static constexpr time::nanoseconds RTT_TIMEOUT = -2_ns; private: ndn::util::RttEstimator m_rttEstimator; diff --git a/daemon/fw/asf-probing-module.cpp b/daemon/fw/asf-probing-module.cpp index 425b39cd..0df1712c 100644 --- a/daemon/fw/asf-probing-module.cpp +++ b/daemon/fw/asf-probing-module.cpp @@ -33,11 +33,7 @@ namespace nfd { namespace fw { namespace asf { -constexpr time::milliseconds ProbingModule::DEFAULT_PROBING_INTERVAL; -constexpr time::milliseconds ProbingModule::MIN_PROBING_INTERVAL; - -static_assert(ProbingModule::DEFAULT_PROBING_INTERVAL < AsfMeasurements::MEASUREMENTS_LIFETIME, - "ProbingModule::DEFAULT_PROBING_INTERVAL must be less than AsfMeasurements::MEASUREMENTS_LIFETIME"); +static_assert(ProbingModule::DEFAULT_PROBING_INTERVAL < AsfMeasurements::MEASUREMENTS_LIFETIME); ProbingModule::ProbingModule(AsfMeasurements& measurements) : m_probingInterval(DEFAULT_PROBING_INTERVAL) diff --git a/daemon/fw/face-table.cpp b/daemon/fw/face-table.cpp index 49d33b60..93567bf1 100644 --- a/daemon/fw/face-table.cpp +++ b/daemon/fw/face-table.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -76,19 +76,20 @@ FaceTable::addReserved(shared_ptr face, FaceId faceId) } void -FaceTable::addImpl(shared_ptr face, FaceId faceId) +FaceTable::addImpl(shared_ptr facePtr, FaceId faceId) { - face->setId(faceId); - auto ret = m_faces.emplace(faceId, face); - BOOST_VERIFY(ret.second); + facePtr->setId(faceId); + auto [it, isNew] = m_faces.try_emplace(faceId, std::move(facePtr)); + BOOST_VERIFY(isNew); + auto& face = *it->second; NFD_LOG_INFO("Added face id=" << faceId << - " remote=" << face->getRemoteUri() << - " local=" << face->getLocalUri()); + " remote=" << face.getRemoteUri() << + " local=" << face.getLocalUri()); - connectFaceClosedSignal(*face, [=] { remove(faceId); }); + connectFaceClosedSignal(face, [this, faceId] { remove(faceId); }); - this->afterAdd(*face); + this->afterAdd(face); } void diff --git a/daemon/fw/forwarder.hpp b/daemon/fw/forwarder.hpp index 47c6e03f..cad93964 100644 --- a/daemon/fw/forwarder.hpp +++ b/daemon/fw/forwarder.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -251,7 +251,7 @@ private: NetworkRegionTable m_networkRegionTable; // allow Strategy (base class) to enter pipelines - friend class fw::Strategy; + friend fw::Strategy; }; } // namespace nfd diff --git a/daemon/fw/retx-suppression-exponential.cpp b/daemon/fw/retx-suppression-exponential.cpp index 114b491e..6158120e 100644 --- a/daemon/fw/retx-suppression-exponential.cpp +++ b/daemon/fw/retx-suppression-exponential.cpp @@ -24,14 +24,11 @@ */ #include "retx-suppression-exponential.hpp" +#include "algorithm.hpp" namespace nfd { namespace fw { -const RetxSuppressionExponential::Duration RetxSuppressionExponential::DEFAULT_INITIAL_INTERVAL = 10_ms; -const RetxSuppressionExponential::Duration RetxSuppressionExponential::DEFAULT_MAX_INTERVAL = 250_ms; -const float RetxSuppressionExponential::DEFAULT_MULTIPLIER = 2.0f; - namespace { class PitInfo final : public StrategyInfo diff --git a/daemon/fw/retx-suppression-exponential.hpp b/daemon/fw/retx-suppression-exponential.hpp index 3c3be606..41d5bdb1 100644 --- a/daemon/fw/retx-suppression-exponential.hpp +++ b/daemon/fw/retx-suppression-exponential.hpp @@ -26,7 +26,6 @@ #ifndef NFD_DAEMON_FW_RETX_SUPPRESSION_EXPONENTIAL_HPP #define NFD_DAEMON_FW_RETX_SUPPRESSION_EXPONENTIAL_HPP -#include "algorithm.hpp" #include "retx-suppression.hpp" #include "strategy.hpp" @@ -83,9 +82,9 @@ private: // non-member operators (hidden friends) } public: - static const Duration DEFAULT_INITIAL_INTERVAL; - static const Duration DEFAULT_MAX_INTERVAL; - static const float DEFAULT_MULTIPLIER; + static constexpr Duration DEFAULT_INITIAL_INTERVAL = 10_ms; + static constexpr Duration DEFAULT_MAX_INTERVAL = 250_ms; + static constexpr float DEFAULT_MULTIPLIER = 2.0f; NFD_PUBLIC_WITH_TESTS_ELSE_PRIVATE: const Duration m_initialInterval; diff --git a/daemon/fw/retx-suppression-fixed.cpp b/daemon/fw/retx-suppression-fixed.cpp index 50ade919..790ce456 100644 --- a/daemon/fw/retx-suppression-fixed.cpp +++ b/daemon/fw/retx-suppression-fixed.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -24,12 +24,11 @@ */ #include "retx-suppression-fixed.hpp" +#include "algorithm.hpp" namespace nfd { namespace fw { -const time::milliseconds RetxSuppressionFixed::DEFAULT_MIN_RETX_INTERVAL = 100_ms; - RetxSuppressionFixed::RetxSuppressionFixed(const time::milliseconds& minRetxInterval) : m_minRetxInterval(minRetxInterval) { diff --git a/daemon/fw/retx-suppression-fixed.hpp b/daemon/fw/retx-suppression-fixed.hpp index 33ee765f..e8af73b9 100644 --- a/daemon/fw/retx-suppression-fixed.hpp +++ b/daemon/fw/retx-suppression-fixed.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2017, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -26,8 +26,8 @@ #ifndef NFD_DAEMON_FW_RETX_SUPPRESSION_FIXED_HPP #define NFD_DAEMON_FW_RETX_SUPPRESSION_FIXED_HPP -#include "algorithm.hpp" #include "retx-suppression.hpp" +#include "table/pit-entry.hpp" namespace nfd { namespace fw { @@ -48,7 +48,7 @@ public: decidePerPitEntry(pit::Entry& pitEntry) const; public: - static const time::milliseconds DEFAULT_MIN_RETX_INTERVAL; + static constexpr time::milliseconds DEFAULT_MIN_RETX_INTERVAL = 100_ms; private: const time::milliseconds m_minRetxInterval; diff --git a/daemon/fw/self-learning-strategy.cpp b/daemon/fw/self-learning-strategy.cpp index 89ca397f..db580504 100644 --- a/daemon/fw/self-learning-strategy.cpp +++ b/daemon/fw/self-learning-strategy.cpp @@ -42,7 +42,7 @@ namespace fw { NFD_LOG_INIT(SelfLearningStrategy); NFD_REGISTER_STRATEGY(SelfLearningStrategy); -const time::milliseconds SelfLearningStrategy::ROUTE_RENEW_LIFETIME(10_min); +constexpr time::milliseconds ROUTE_RENEW_LIFETIME = 10_min; SelfLearningStrategy::SelfLearningStrategy(Forwarder& forwarder, const Name& name) : Strategy(forwarder) @@ -191,11 +191,11 @@ SelfLearningStrategy::asyncProcessData(const shared_ptr& pitEntry, c // (the PIT entry's expiry timer was set to 0 before dispatching) this->setExpiryTimer(pitEntry, 1_s); - runOnRibIoService([pitEntryWeak = weak_ptr{pitEntry}, inFaceId = inFace.getId(), data, this] { + runOnRibIoService([this, pitEntryWeak = weak_ptr{pitEntry}, inFaceId = inFace.getId(), data] { rib::Service::get().getRibManager().slFindAnn(data.getName(), - [pitEntryWeak, inFaceId, data, this] (std::optional paOpt) { + [this, pitEntryWeak, inFaceId, data] (std::optional paOpt) { if (paOpt) { - runOnMainIoService([pitEntryWeak, inFaceId, data, pa = std::move(*paOpt), this] { + runOnMainIoService([this, pitEntryWeak, inFaceId, data, pa = std::move(*paOpt)] { auto pitEntry = pitEntryWeak.lock(); auto inFace = this->getFace(inFaceId); if (pitEntry && inFace) { diff --git a/daemon/fw/self-learning-strategy.hpp b/daemon/fw/self-learning-strategy.hpp index bb4f6f78..47e59af9 100644 --- a/daemon/fw/self-learning-strategy.hpp +++ b/daemon/fw/self-learning-strategy.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -136,9 +136,6 @@ private: // operations */ void renewRoute(const Name& name, FaceId inFaceId, time::milliseconds maxLifetime); - -private: - static const time::milliseconds ROUTE_RENEW_LIFETIME; }; } // namespace fw diff --git a/daemon/fw/strategy.hpp b/daemon/fw/strategy.hpp index 4e162bd8..570f2194 100644 --- a/daemon/fw/strategy.hpp +++ b/daemon/fw/strategy.hpp @@ -52,11 +52,10 @@ public: // registry { BOOST_ASSERT(strategyName.size() > 1); BOOST_ASSERT(strategyName.at(-1).isVersion()); - Registry& registry = getRegistry(); - BOOST_ASSERT(registry.count(strategyName) == 0); - registry[strategyName] = [] (auto&&... args) { + auto r = getRegistry().insert_or_assign(strategyName, [] (auto&&... args) { return make_unique(std::forward(args)...); - }; + }); + BOOST_VERIFY(r.second); } /** \return Whether a strategy instance can be created from \p instanceName diff --git a/daemon/fw/unsolicited-data-policy.cpp b/daemon/fw/unsolicited-data-policy.cpp index 8cf59d97..b29b8273 100644 --- a/daemon/fw/unsolicited-data-policy.cpp +++ b/daemon/fw/unsolicited-data-policy.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ -/** - * Copyright (c) 2014-2016, Regents of the University of California, +/* + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -24,6 +24,7 @@ */ #include "unsolicited-data-policy.hpp" + #include #include @@ -70,7 +71,7 @@ const std::string DropAllUnsolicitedDataPolicy::POLICY_NAME("drop-all"); NFD_REGISTER_UNSOLICITED_DATA_POLICY(DropAllUnsolicitedDataPolicy); UnsolicitedDataDecision -DropAllUnsolicitedDataPolicy::decide(const Face& inFace, const Data& data) const +DropAllUnsolicitedDataPolicy::decide(const Face&, const Data&) const { return UnsolicitedDataDecision::DROP; } @@ -79,7 +80,7 @@ const std::string AdmitLocalUnsolicitedDataPolicy::POLICY_NAME("admit-local"); NFD_REGISTER_UNSOLICITED_DATA_POLICY(AdmitLocalUnsolicitedDataPolicy); UnsolicitedDataDecision -AdmitLocalUnsolicitedDataPolicy::decide(const Face& inFace, const Data& data) const +AdmitLocalUnsolicitedDataPolicy::decide(const Face& inFace, const Data&) const { if (inFace.getScope() == ndn::nfd::FACE_SCOPE_LOCAL) { return UnsolicitedDataDecision::CACHE; @@ -91,7 +92,7 @@ const std::string AdmitNetworkUnsolicitedDataPolicy::POLICY_NAME("admit-network" NFD_REGISTER_UNSOLICITED_DATA_POLICY(AdmitNetworkUnsolicitedDataPolicy); UnsolicitedDataDecision -AdmitNetworkUnsolicitedDataPolicy::decide(const Face& inFace, const Data& data) const +AdmitNetworkUnsolicitedDataPolicy::decide(const Face& inFace, const Data&) const { if (inFace.getScope() == ndn::nfd::FACE_SCOPE_NON_LOCAL) { return UnsolicitedDataDecision::CACHE; @@ -103,7 +104,7 @@ const std::string AdmitAllUnsolicitedDataPolicy::POLICY_NAME("admit-all"); NFD_REGISTER_UNSOLICITED_DATA_POLICY(AdmitAllUnsolicitedDataPolicy); UnsolicitedDataDecision -AdmitAllUnsolicitedDataPolicy::decide(const Face& inFace, const Data& data) const +AdmitAllUnsolicitedDataPolicy::decide(const Face&, const Data&) const { return UnsolicitedDataDecision::CACHE; } diff --git a/daemon/fw/unsolicited-data-policy.hpp b/daemon/fw/unsolicited-data-policy.hpp index 5d562a1f..486903a3 100644 --- a/daemon/fw/unsolicited-data-policy.hpp +++ b/daemon/fw/unsolicited-data-policy.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -31,7 +31,8 @@ namespace nfd { namespace fw { -/** \brief a decision made by UnsolicitedDataPolicy +/** + * \brief Decision made by UnsolicitedDataPolicy */ enum class UnsolicitedDataDecision { DROP, ///< the Data should be dropped @@ -41,11 +42,12 @@ enum class UnsolicitedDataDecision { std::ostream& operator<<(std::ostream& os, UnsolicitedDataDecision d); -/** \brief determines how to process an unsolicited Data +/** + * \brief Determines how to process an unsolicited Data packet * - * An incoming Data is unsolicited if it does not match any PIT entry. - * This class assists forwarding pipelines to decide whether to drop an unsolicited Data - * or admit it into the ContentStore. + * An incoming Data packet is *unsolicited* if it does not match any PIT entry. + * This class assists forwarding pipelines to decide whether to drop an unsolicited Data + * or admit it into the ContentStore. */ class UnsolicitedDataPolicy : noncopyable { @@ -61,9 +63,9 @@ public: // registry static void registerPolicy(const std::string& policyName = P::POLICY_NAME) { - Registry& registry = getRegistry(); - BOOST_ASSERT(registry.count(policyName) == 0); - registry[policyName] = [] { return make_unique

(); }; + BOOST_ASSERT(!policyName.empty()); + auto r = getRegistry().insert_or_assign(policyName, [] { return make_unique

(); }); + BOOST_VERIFY(r.second); } /** \return an UnsolicitedDataPolicy identified by \p policyName, @@ -78,14 +80,15 @@ public: // registry getPolicyNames(); private: - typedef std::function()> CreateFunc; - typedef std::map Registry; // indexed by policy name + using CreateFunc = std::function()>; + using Registry = std::map; // indexed by policy name static Registry& getRegistry(); }; -/** \brief drops all unsolicited Data +/** + * \brief Drops all unsolicited Data */ class DropAllUnsolicitedDataPolicy final : public UnsolicitedDataPolicy { @@ -97,7 +100,8 @@ public: static const std::string POLICY_NAME; }; -/** \brief admits unsolicited Data from local faces +/** + * \brief Admits unsolicited Data from local faces */ class AdmitLocalUnsolicitedDataPolicy final : public UnsolicitedDataPolicy { @@ -109,7 +113,8 @@ public: static const std::string POLICY_NAME; }; -/** \brief admits unsolicited Data from non-local faces +/** + * \brief Admits unsolicited Data from non-local faces */ class AdmitNetworkUnsolicitedDataPolicy final : public UnsolicitedDataPolicy { @@ -121,7 +126,8 @@ public: static const std::string POLICY_NAME; }; -/** \brief admits all unsolicited Data +/** + * \brief Admits all unsolicited Data */ class AdmitAllUnsolicitedDataPolicy final : public UnsolicitedDataPolicy { @@ -133,16 +139,18 @@ public: static const std::string POLICY_NAME; }; -/** \brief The default UnsolicitedDataPolicy +/** + * \brief The default UnsolicitedDataPolicy */ using DefaultUnsolicitedDataPolicy = DropAllUnsolicitedDataPolicy; } // namespace fw } // namespace nfd -/** \brief registers an unsolicited data policy - * \param P a subclass of nfd::fw::UnsolicitedDataPolicy; - * P::POLICY_NAME must be a string that contains policy name +/** + * \brief Registers an unsolicited data policy + * \param P A subclass of nfd::fw::UnsolicitedDataPolicy. \p P must have a static data + * member `POLICY_NAME` convertible to std::string that contains the policy name. */ #define NFD_REGISTER_UNSOLICITED_DATA_POLICY(P) \ static class NfdAuto ## P ## UnsolicitedDataPolicyRegistrationClass \ diff --git a/daemon/mgmt/cs-manager.cpp b/daemon/mgmt/cs-manager.cpp index eaf2cdaf..36d7014b 100644 --- a/daemon/mgmt/cs-manager.cpp +++ b/daemon/mgmt/cs-manager.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -31,8 +31,6 @@ namespace nfd { -constexpr size_t CsManager::ERASE_LIMIT; - CsManager::CsManager(Cs& cs, const ForwarderCounters& fwCounters, Dispatcher& dispatcher, CommandAuthenticator& authenticator) : ManagerBase("cs", dispatcher, authenticator) @@ -101,8 +99,7 @@ CsManager::erase(const ControlParameters& parameters, } void -CsManager::serveInfo(const Name& topPrefix, const Interest& interest, - ndn::mgmt::StatusDatasetContext& context) const +CsManager::serveInfo(const Name&, const Interest&, ndn::mgmt::StatusDatasetContext& context) const { ndn::nfd::CsInfo info; info.setCapacity(m_cs.getLimit()); diff --git a/daemon/mgmt/face-manager.cpp b/daemon/mgmt/face-manager.cpp index 839a6fb4..cc890618 100644 --- a/daemon/mgmt/face-manager.cpp +++ b/daemon/mgmt/face-manager.cpp @@ -260,7 +260,7 @@ FaceManager::updateFace(const Interest& interest, const ndn::mgmt::CommandContinuation& done) { FaceId faceId = parameters.getFaceId(); - if (faceId == 0) { // Self-update + if (faceId == face::INVALID_FACEID) { // Self-update auto incomingFaceIdTag = interest.getTag(); if (incomingFaceIdTag == nullptr) { NFD_LOG_TRACE("unable to determine face for self-update"); diff --git a/daemon/mgmt/fib-manager.cpp b/daemon/mgmt/fib-manager.cpp index f8a99d8c..474d616a 100644 --- a/daemon/mgmt/fib-manager.cpp +++ b/daemon/mgmt/fib-manager.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -53,7 +53,7 @@ FibManager::FibManager(Fib& fib, const FaceTable& faceTable, } void -FibManager::addNextHop(const Name& topPrefix, const Interest& interest, +FibManager::addNextHop(const Name&, const Interest& interest, ControlParameters parameters, const ndn::mgmt::CommandContinuation& done) { @@ -84,7 +84,7 @@ FibManager::addNextHop(const Name& topPrefix, const Interest& interest, } void -FibManager::removeNextHop(const Name& topPrefix, const Interest& interest, +FibManager::removeNextHop(const Name&, const Interest& interest, ControlParameters parameters, const ndn::mgmt::CommandContinuation& done) { @@ -121,7 +121,7 @@ FibManager::removeNextHop(const Name& topPrefix, const Interest& interest, } void -FibManager::listEntries(const Name& topPrefix, const Interest& interest, +FibManager::listEntries(const Name&, const Interest&, ndn::mgmt::StatusDatasetContext& context) { for (const auto& entry : m_fib) { @@ -142,9 +142,9 @@ FibManager::listEntries(const Name& topPrefix, const Interest& interest, void FibManager::setFaceForSelfRegistration(const Interest& request, ControlParameters& parameters) { - bool isSelfRegistration = (parameters.getFaceId() == 0); + bool isSelfRegistration = parameters.getFaceId() == face::INVALID_FACEID; if (isSelfRegistration) { - shared_ptr incomingFaceIdTag = request.getTag(); + auto incomingFaceIdTag = request.getTag(); // NDNLPv2 says "application MUST be prepared to receive a packet without IncomingFaceId field", // but it's fine to assert IncomingFaceId is available, because InternalFace lives inside NFD // and is initialized synchronously with IncomingFaceId field enabled. diff --git a/daemon/mgmt/rib-manager.cpp b/daemon/mgmt/rib-manager.cpp index d66baea1..24d52b71 100644 --- a/daemon/mgmt/rib-manager.cpp +++ b/daemon/mgmt/rib-manager.cpp @@ -42,11 +42,9 @@ using rib::Route; NFD_LOG_INIT(RibManager); -static const std::string MGMT_MODULE_NAME = "rib"; -static const Name LOCALHOST_TOP_PREFIX = "/localhost/nfd"; -static const time::seconds ACTIVE_FACE_FETCH_INTERVAL = 5_min; - -const Name RibManager::LOCALHOP_TOP_PREFIX = "/localhop/nfd"; +const std::string MGMT_MODULE_NAME = "rib"; +const Name LOCALHOST_TOP_PREFIX = "/localhost/nfd"; +const time::seconds ACTIVE_FACE_FETCH_INTERVAL = 5_min; RibManager::RibManager(rib::Rib& rib, ndn::Face& face, ndn::KeyChain& keyChain, ndn::nfd::Controller& nfdController, Dispatcher& dispatcher) diff --git a/daemon/mgmt/rib-manager.hpp b/daemon/mgmt/rib-manager.hpp index ac2a3247..ec2394d0 100644 --- a/daemon/mgmt/rib-manager.hpp +++ b/daemon/mgmt/rib-manager.hpp @@ -240,7 +240,7 @@ NFD_PUBLIC_WITH_TESTS_ELSE_PRIVATE: onNotification(const ndn::nfd::FaceEventNotification& notification); public: - static const Name LOCALHOP_TOP_PREFIX; + static inline const Name LOCALHOP_TOP_PREFIX{"/localhop/nfd"}; private: rib::Rib& m_rib; diff --git a/daemon/mgmt/strategy-choice-manager.cpp b/daemon/mgmt/strategy-choice-manager.cpp index 9be09d2b..ea0c0560 100644 --- a/daemon/mgmt/strategy-choice-manager.cpp +++ b/daemon/mgmt/strategy-choice-manager.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -63,9 +63,7 @@ StrategyChoiceManager::setStrategy(ControlParameters parameters, } NFD_LOG_DEBUG("strategy-choice/set(" << prefix << "," << strategy << "): OK"); - bool hasEntry = false; - Name instanceName; - std::tie(hasEntry, instanceName) = m_table.get(prefix); + auto [hasEntry, instanceName] = m_table.get(prefix); BOOST_ASSERT_MSG(hasEntry, "StrategyChoice entry must exist after StrategyChoice::insert"); parameters.setStrategy(instanceName); return done(ControlResponse(200, "OK").setBody(parameters.wireEncode())); diff --git a/daemon/mgmt/tables-config-section.cpp b/daemon/mgmt/tables-config-section.cpp index f6adced6..f693a73b 100644 --- a/daemon/mgmt/tables-config-section.cpp +++ b/daemon/mgmt/tables-config-section.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -28,7 +28,7 @@ namespace nfd { -const size_t DEFAULT_CS_MAX_PACKETS = 65536; +constexpr size_t DEFAULT_CS_MAX_PACKETS = 65536; TablesConfigSection::TablesConfigSection(Forwarder& forwarder) : m_forwarder(forwarder) @@ -118,22 +118,19 @@ TablesConfigSection::processConfig(const ConfigSection& section, bool isDryRun, void TablesConfigSection::processStrategyChoiceSection(const ConfigSection& section, bool isDryRun) { - using fw::Strategy; - std::map choices; for (const auto& prefixAndStrategy : section) { Name prefix(prefixAndStrategy.first); Name strategy(prefixAndStrategy.second.get_value()); - if (!Strategy::canCreate(strategy)) { - NDN_THROW(ConfigFile::Error( - "Unknown strategy '" + prefixAndStrategy.second.get_value() + - "' for prefix '" + prefix.toUri() + "' in section 'strategy_choice'")); + if (!fw::Strategy::canCreate(strategy)) { + NDN_THROW(ConfigFile::Error("Unknown strategy '" + prefixAndStrategy.second.get_value() + + "' for prefix '" + prefix.toUri() + "' in section 'strategy_choice'")); } - if (!choices.emplace(prefix, strategy).second) { - NDN_THROW(ConfigFile::Error( - "Duplicate strategy choice for prefix '" + prefix.toUri() + "' in section 'strategy_choice'")); + if (!choices.try_emplace(prefix, std::move(strategy)).second) { + NDN_THROW(ConfigFile::Error("Duplicate strategy choice for prefix '" + prefix.toUri() + + "' in section 'strategy_choice'")); } } diff --git a/daemon/rib/readvertise/host-to-gateway-readvertise-policy.cpp b/daemon/rib/readvertise/host-to-gateway-readvertise-policy.cpp index 89f11fd2..5aa6e3b8 100644 --- a/daemon/rib/readvertise/host-to-gateway-readvertise-policy.cpp +++ b/daemon/rib/readvertise/host-to-gateway-readvertise-policy.cpp @@ -33,8 +33,8 @@ namespace nfd { namespace rib { -static const name::Component IGNORE_COMPONENT("nrd"); -static const time::seconds DEFAULT_REFRESH_INTERVAL = 25_s; +const name::Component IGNORE_COMPONENT("nrd"); +const time::seconds DEFAULT_REFRESH_INTERVAL = 25_s; HostToGatewayReadvertisePolicy::HostToGatewayReadvertisePolicy(const ndn::KeyChain& keyChain, const ConfigSection& section) diff --git a/daemon/rib/readvertise/readvertise.cpp b/daemon/rib/readvertise/readvertise.cpp index addad72c..ded568d6 100644 --- a/daemon/rib/readvertise/readvertise.cpp +++ b/daemon/rib/readvertise/readvertise.cpp @@ -34,8 +34,8 @@ namespace rib { NFD_LOG_INIT(Readvertise); -const time::milliseconds Readvertise::RETRY_DELAY_MIN = 50_s; -const time::milliseconds Readvertise::RETRY_DELAY_MAX = 1_h; +constexpr time::milliseconds RETRY_DELAY_MIN = 50_s; +constexpr time::milliseconds RETRY_DELAY_MAX = 1_h; static time::milliseconds randomizeTimer(time::milliseconds baseTimer) @@ -74,20 +74,16 @@ Readvertise::afterAddRoute(const RibRouteRef& ribRoute) return; } - ReadvertisedRouteContainer::iterator rrIt; - bool isNew = false; - std::tie(rrIt, isNew) = m_rrs.emplace(action->prefix); - - if (!isNew && rrIt->signer != action->signer) { + auto [rrIt, isNewRr] = m_rrs.emplace(action->prefix); + if (!isNewRr && rrIt->signer != action->signer) { NFD_LOG_WARN("add-route " << ribRoute.entry->getName() << '(' << ribRoute.route->faceId << - ',' << ribRoute.route->origin << ") readvertising-as " << action->prefix << + ',' << ribRoute.route->origin << ") readvertising-as " << action->prefix << " old-signer " << rrIt->signer << " new-signer " << action->signer); } rrIt->signer = action->signer; - RouteRrIndex::iterator indexIt; - std::tie(indexIt, isNew) = m_routeToRr.emplace(ribRoute, rrIt); - BOOST_ASSERT(isNew); + bool isNewInMap = m_routeToRr.try_emplace(ribRoute, rrIt).second; + BOOST_VERIFY(isNewInMap); if (rrIt->nRibRoutes++ > 0) { NFD_LOG_DEBUG("add-route " << ribRoute.entry->getName() << '(' << ribRoute.route->faceId << diff --git a/daemon/rib/readvertise/readvertise.hpp b/daemon/rib/readvertise/readvertise.hpp index 871702fc..aeaa8233 100644 --- a/daemon/rib/readvertise/readvertise.hpp +++ b/daemon/rib/readvertise/readvertise.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -68,18 +68,14 @@ private: withdraw(ReadvertisedRouteContainer::iterator rrIt); private: - /** \brief maps from RIB route to readvertised route derived from RIB route(s) - */ - using RouteRrIndex = std::map; - - static const time::milliseconds RETRY_DELAY_MIN; - static const time::milliseconds RETRY_DELAY_MAX; - unique_ptr m_policy; unique_ptr m_destination; ReadvertisedRouteContainer m_rrs; - RouteRrIndex m_routeToRr; + /** + * \brief maps from RIB route to readvertised route derived from RIB route(s) + */ + std::map m_routeToRr; signal::ScopedConnection m_addRouteConn; signal::ScopedConnection m_removeRouteConn; diff --git a/daemon/rib/rib-entry.cpp b/daemon/rib/rib-entry.cpp index 6acae09f..1710aff5 100644 --- a/daemon/rib/rib-entry.cpp +++ b/daemon/rib/rib-entry.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -271,7 +271,7 @@ RibEntry::getPrefixAnnouncement(time::milliseconds minExpiration, ndn::PrefixAnnouncement ann; ann.setAnnouncedName(m_name); - ann.setExpiration(ndn::clamp( + ann.setExpiration(std::clamp( time::duration_cast(entryExpiry - time::steady_clock::now()), minExpiration, maxExpiration)); return ann; @@ -280,16 +280,12 @@ RibEntry::getPrefixAnnouncement(time::milliseconds minExpiration, std::ostream& operator<<(std::ostream& os, const RibEntry& entry) { - os << "RibEntry {\n"; - os << " Name: " << entry.getName() << "\n"; - + os << "RibEntry {\n" + << " Name: " << entry.getName() << "\n"; for (const Route& route : entry) { os << " " << route << "\n"; } - - os << "}"; - - return os; + return os << "}"; } } // namespace rib diff --git a/daemon/rib/rib-entry.hpp b/daemon/rib/rib-entry.hpp index 03cfc8cb..79f16276 100644 --- a/daemon/rib/rib-entry.hpp +++ b/daemon/rib/rib-entry.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -33,19 +33,15 @@ namespace nfd { namespace rib { -/** \brief Represents a RIB entry, which contains one or more Routes with the same prefix. +/** + * \brief Represents a RIB entry, which contains one or more Routes with the same prefix. */ class RibEntry : public std::enable_shared_from_this { public: - typedef std::list RouteList; - typedef RouteList::iterator iterator; - typedef RouteList::const_iterator const_iterator; - - RibEntry() - : m_nRoutesWithCaptureSet(0) - { - } + using RouteList = std::list; + using iterator = RouteList::iterator; + using const_iterator = RouteList::const_iterator; void setName(const Name& prefix); @@ -210,7 +206,7 @@ private: * If the number is greater than zero, a route on the namespace has its capture * flag set which means the namespace should not inherit any routes. */ - uint64_t m_nRoutesWithCaptureSet; + uint64_t m_nRoutesWithCaptureSet = 0; }; inline void @@ -228,7 +224,7 @@ RibEntry::getName() const inline void RibEntry::setParent(shared_ptr parent) { - m_parent = parent; + m_parent = std::move(parent); } inline shared_ptr diff --git a/daemon/rib/rib-update-batch.hpp b/daemon/rib/rib-update-batch.hpp index f72a9e8a..f3facb37 100644 --- a/daemon/rib/rib-update-batch.hpp +++ b/daemon/rib/rib-update-batch.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -33,20 +33,24 @@ namespace nfd { namespace rib { -typedef std::list RibUpdateList; +using RibUpdateList = std::list; -/** \brief Represents a collection of RibUpdates to be applied to a single FaceId. +/** + * \brief Represents a collection of RibUpdates to be applied to a single FaceId. */ class RibUpdateBatch { public: - typedef RibUpdateList::const_iterator const_iterator; + using const_iterator = RibUpdateList::const_iterator; explicit RibUpdateBatch(uint64_t faceId); uint64_t - getFaceId() const; + getFaceId() const + { + return m_faceId; + } void add(const RibUpdate& update); @@ -65,12 +69,6 @@ private: RibUpdateList m_updates; }; -inline uint64_t -RibUpdateBatch::getFaceId() const -{ - return m_faceId; -} - } // namespace rib } // namespace nfd diff --git a/daemon/rib/rib-update.cpp b/daemon/rib/rib-update.cpp index 8efe327f..be2636dd 100644 --- a/daemon/rib/rib-update.cpp +++ b/daemon/rib/rib-update.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ -/** - * Copyright (c) 2014-2015, Regents of the University of California, +/* + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -28,13 +28,8 @@ namespace nfd { namespace rib { -RibUpdate::RibUpdate() -{ - -} - std::ostream& -operator<<(std::ostream& os, const RibUpdate::Action action) +operator<<(std::ostream& os, RibUpdate::Action action) { switch (action) { case RibUpdate::REGISTER: @@ -47,22 +42,18 @@ operator<<(std::ostream& os, const RibUpdate::Action action) os << "REMOVE_FACE"; break; } - return os; } std::ostream& operator<<(std::ostream& os, const RibUpdate& update) { - os << "RibUpdate {\n"; - os << " Name: " << update.getName() << "\n"; - os << " Action: " << update.getAction() << "\n"; - os << " " << update.getRoute() << "\n"; - os << "}"; - - return os; + return os << "RibUpdate {\n" + << " Name: " << update.getName() << "\n" + << " Action: " << update.getAction() << "\n" + << " " << update.getRoute() << "\n" + << "}"; } - } // namespace rib } // namespace nfd diff --git a/daemon/rib/rib-update.hpp b/daemon/rib/rib-update.hpp index ad5a390b..bcdb342e 100644 --- a/daemon/rib/rib-update.hpp +++ b/daemon/rib/rib-update.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -32,27 +32,23 @@ namespace nfd { namespace rib { -/** RibUpdate - * \brief represents a route that will be added to or removed from a namespace - * - * \note This type is copyable so that it can be stored in STL containers. +/** + * \brief Represents a route that will be added to or removed from a namespace + * \note This type is copyable so that it can be stored in STL containers. */ class RibUpdate { public: enum Action { - REGISTER = 0, - UNREGISTER = 1, - - /** \brief An update triggered by a face destruction notification - * - * \note indicates a Route needs to be removed after a face is destroyed + REGISTER = 0, + UNREGISTER = 1, + /** + * \brief An update triggered by a face destruction notification + * \note indicates a Route needs to be removed after a face is destroyed */ - REMOVE_FACE = 2 + REMOVE_FACE = 2, }; - RibUpdate(); - RibUpdate& setAction(Action action); @@ -117,7 +113,7 @@ RibUpdate::getRoute() const } std::ostream& -operator<<(std::ostream& os, const RibUpdate::Action action); +operator<<(std::ostream& os, RibUpdate::Action action); std::ostream& operator<<(std::ostream& os, const RibUpdate& update); diff --git a/daemon/rib/rib.cpp b/daemon/rib/rib.cpp index a81e77a5..fe4db0b6 100644 --- a/daemon/rib/rib.cpp +++ b/daemon/rib/rib.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -96,10 +96,7 @@ Rib::insert(const Name& prefix, const Route& route) // Name prefix exists if (ribIt != m_rib.end()) { shared_ptr entry(ribIt->second); - - RibEntry::iterator entryIt; - bool didInsert = false; - std::tie(entryIt, didInsert) = entry->insertRoute(route); + auto [entryIt, didInsert] = entry->insertRoute(route); if (didInsert) { // The route was new and we successfully inserted it. @@ -139,15 +136,13 @@ Rib::insert(const Name& prefix, const Route& route) parent->addChild(entry); } - RibEntryList children = findDescendants(prefix); - + auto children = findDescendants(prefix); for (const auto& child : children) { if (child->getParent() == parent) { // Remove child from parent and inherit parent's child if (parent != nullptr) { parent->removeChild(child); } - entry->addChild(child); } } @@ -229,12 +224,12 @@ Rib::findDescendants(const Name& prefix) const { std::list> children; - RibTable::const_iterator it = m_rib.find(prefix); + auto it = m_rib.find(prefix); if (it != m_rib.end()) { ++it; for (; it != m_rib.end(); ++it) { if (prefix.isPrefixOf(it->first)) { - children.push_back((it->second)); + children.push_back(it->second); } else { break; @@ -250,9 +245,9 @@ Rib::findDescendantsForNonInsertedName(const Name& prefix) const { std::list> children; - for (const auto& pair : m_rib) { - if (prefix.isPrefixOf(pair.first)) { - children.push_back(pair.second); + for (const auto& [name, ribEntry] : m_rib) { + if (prefix.isPrefixOf(name)) { + children.push_back(ribEntry); } } @@ -268,7 +263,6 @@ Rib::eraseEntry(RibTable::iterator it) } shared_ptr entry(it->second); - shared_ptr parent = entry->getParent(); // Remove self from parent's children @@ -293,7 +287,7 @@ Rib::eraseEntry(RibTable::iterator it) auto nextIt = m_rib.erase(it); - // do something after erasing an entry. + // do something after erasing an entry afterEraseEntry(entry->getName()); return nextIt; @@ -304,10 +298,9 @@ Rib::getAncestorRoutes(const RibEntry& entry) const { RouteSet ancestorRoutes(&sortRoutes); - shared_ptr parent = entry.getParent(); - + auto parent = entry.getParent(); while (parent != nullptr) { - for (const Route& route : parent->getRoutes()) { + for (const auto& route : parent->getRoutes()) { if (route.isChildInherit()) { ancestorRoutes.insert(route); } @@ -328,10 +321,9 @@ Rib::getAncestorRoutes(const Name& name) const { RouteSet ancestorRoutes(&sortRoutes); - shared_ptr parent = findParent(name); - + auto parent = findParent(name); while (parent != nullptr) { - for (const Route& route : parent->getRoutes()) { + for (const auto& route : parent->getRoutes()) { if (route.isChildInherit()) { ancestorRoutes.insert(route); } @@ -353,9 +345,7 @@ Rib::beginApplyUpdate(const RibUpdate& update, const Rib::UpdateFailureCallback& onFailure) { BOOST_ASSERT(m_fibUpdater != nullptr); - addUpdateToQueue(update, onSuccess, onFailure); - sendBatchFromQueue(); } @@ -372,11 +362,11 @@ Rib::beginRemoveFace(uint64_t faceId) void Rib::beginRemoveFailedFaces(const std::set& activeFaceIds) { - for (auto it = m_faceEntries.begin(); it != m_faceEntries.end(); ++it) { - if (activeFaceIds.count(it->first) > 0) { + for (const auto& [faceId, ribEntry] : m_faceEntries) { + if (activeFaceIds.count(faceId) > 0) { continue; } - enqueueRemoveFace(*it->second, it->first); + enqueueRemoveFace(*ribEntry, faceId); } sendBatchFromQueue(); } @@ -428,7 +418,6 @@ Rib::sendBatchFromQueue() auto fibSuccessCb = std::bind(&Rib::onFibUpdateSuccess, this, batch, _1, item.managerSuccessCallback); auto fibFailureCb = std::bind(&Rib::onFibUpdateFailure, this, item.managerFailureCallback, _1, _2); - m_fibUpdater->computeAndSendFibUpdates(batch, fibSuccessCb, fibFailureCb); } diff --git a/daemon/rib/rib.hpp b/daemon/rib/rib.hpp index dbfdba82..f6912c38 100644 --- a/daemon/rib/rib.hpp +++ b/daemon/rib/rib.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -248,7 +248,7 @@ private: UpdateQueue m_updateBatches; bool m_isUpdateInProgress = false; - friend class FibUpdater; + friend FibUpdater; }; std::ostream& diff --git a/daemon/rib/service.cpp b/daemon/rib/service.cpp index 0c674b39..d850ed24 100644 --- a/daemon/rib/service.cpp +++ b/daemon/rib/service.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -43,8 +43,6 @@ namespace rib { NFD_LOG_INIT(RibService); -Service* Service::s_instance = nullptr; - const std::string CFG_RIB = "rib"; const std::string CFG_LOCALHOST_SECURITY = "localhost_security"; const std::string CFG_LOCALHOP_SECURITY = "localhop_security"; @@ -52,8 +50,8 @@ const std::string CFG_PA_VALIDATION = "prefix_announcement_validation"; const std::string CFG_PREFIX_PROPAGATE = "auto_prefix_propagate"; const std::string CFG_READVERTISE_NLSR = "readvertise_nlsr"; const Name READVERTISE_NLSR_PREFIX = "/localhost/nlsr"; -const uint64_t PROPAGATE_DEFAULT_COST = 15; -const time::milliseconds PROPAGATE_DEFAULT_TIMEOUT = 10_s; +constexpr uint64_t PROPAGATE_DEFAULT_COST = 15; +constexpr time::milliseconds PROPAGATE_DEFAULT_TIMEOUT = 10_s; static ConfigSection loadConfigSectionFromFile(const std::string& filename) @@ -64,10 +62,7 @@ loadConfigSectionFromFile(const std::string& filename) return config; } -/** - * \brief Look into the config file and construct appropriate transport to communicate with NFD - * If NFD-RIB instance was initialized with config file, INFO format is assumed - */ +// Look into NFD's config file and construct an appropriate transport to communicate with NFD. static shared_ptr makeLocalNfdTransport(const ConfigSection& config) { diff --git a/daemon/rib/service.hpp b/daemon/rib/service.hpp index ca5f57bc..89280111 100644 --- a/daemon/rib/service.hpp +++ b/daemon/rib/service.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -107,7 +107,7 @@ private: applyConfig(const ConfigSection& section, const std::string& filename); private: - static Service* s_instance; + static inline Service* s_instance = nullptr; ndn::KeyChain& m_keyChain; ndn::Face m_face; diff --git a/daemon/table/cs-policy-lru.cpp b/daemon/table/cs-policy-lru.cpp index 56b21ecd..1b477aa2 100644 --- a/daemon/table/cs-policy-lru.cpp +++ b/daemon/table/cs-policy-lru.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -71,17 +71,15 @@ LruPolicy::evictEntries() BOOST_ASSERT(!m_queue.empty()); EntryRef i = m_queue.front(); m_queue.pop_front(); - this->emitSignal(beforeEvict, i); + emitSignal(beforeEvict, i); } } void LruPolicy::insertToQueue(EntryRef i, bool isNewEntry) { - Queue::iterator it; - bool isNew = false; // push_back only if i does not exist - std::tie(it, isNew) = m_queue.push_back(i); + auto [it, isNew] = m_queue.push_back(i); BOOST_ASSERT(isNew == isNewEntry); if (!isNewEntry) { diff --git a/daemon/table/cs-policy.cpp b/daemon/table/cs-policy.cpp index b51aac17..6b24eb35 100644 --- a/daemon/table/cs-policy.cpp +++ b/daemon/table/cs-policy.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -59,7 +59,7 @@ Policy::getPolicyNames() return policyNames; } -Policy::Policy(const std::string& policyName) +Policy::Policy(std::string_view policyName) : m_policyName(policyName) { } diff --git a/daemon/table/cs-policy.hpp b/daemon/table/cs-policy.hpp index fb599907..9a4c6ed9 100644 --- a/daemon/table/cs-policy.hpp +++ b/daemon/table/cs-policy.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -33,7 +33,8 @@ namespace cs { class Cs; -/** \brief represents a CS replacement policy +/** + * \brief Represents a CS replacement policy */ class Policy : noncopyable { @@ -42,9 +43,9 @@ public: // registry static void registerPolicy(const std::string& policyName = P::POLICY_NAME) { - Registry& registry = getRegistry(); - BOOST_ASSERT(registry.count(policyName) == 0); - registry[policyName] = [] { return make_unique

(); }; + BOOST_ASSERT(!policyName.empty()); + auto r = getRegistry().insert_or_assign(policyName, [] { return make_unique

(); }); + BOOST_VERIFY(r.second); } /** \return a cs::Policy identified by \p policyName, @@ -59,9 +60,6 @@ public: // registry getPolicyNames(); public: - explicit - Policy(const std::string& policyName); - virtual ~Policy() = default; @@ -190,6 +188,9 @@ protected: evictEntries() = 0; protected: + explicit + Policy(std::string_view policyName); + DECLARE_SIGNAL_EMIT(beforeEvict) private: // registry @@ -200,7 +201,7 @@ private: // registry getRegistry(); private: - std::string m_policyName; + const std::string m_policyName; size_t m_limit; Cs* m_cs; }; diff --git a/daemon/table/cs.cpp b/daemon/table/cs.cpp index b240e3de..5fc83019 100644 --- a/daemon/table/cs.cpp +++ b/daemon/table/cs.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -56,7 +56,7 @@ Cs::insert(const Data& data, bool isUnsolicited) NFD_LOG_DEBUG("insert " << data.getName()); // recognize CachePolicy - shared_ptr tag = data.getTag(); + auto tag = data.getTag(); if (tag != nullptr) { lp::CachePolicyType policy = tag->get().getPolicy(); if (policy == lp::CachePolicyType::NO_CACHE) { @@ -64,10 +64,8 @@ Cs::insert(const Data& data, bool isUnsolicited) } } - const_iterator it; - bool isNewEntry = false; - std::tie(it, isNewEntry) = m_table.emplace(data.shared_from_this(), isUnsolicited); - Entry& entry = const_cast(*it); + auto [it, isNewEntry] = m_table.emplace(data.shared_from_this(), isUnsolicited); + auto& entry = const_cast(*it); entry.updateFreshUntil(); @@ -76,7 +74,6 @@ Cs::insert(const Data& data, bool isUnsolicited) if (entry.isUnsolicited() && !isUnsolicited) { entry.clearUnsolicited(); } - m_policy->afterRefresh(it); } else { @@ -89,7 +86,7 @@ Cs::findPrefixRange(const Name& prefix) const { auto first = m_table.lower_bound(prefix); auto last = m_table.end(); - if (prefix.size() > 0) { + if (!prefix.empty()) { last = m_table.lower_bound(prefix.getSuccessor()); } return {first, last}; diff --git a/daemon/table/dead-nonce-list.cpp b/daemon/table/dead-nonce-list.cpp index 55bf3463..6149fd6b 100644 --- a/daemon/table/dead-nonce-list.cpp +++ b/daemon/table/dead-nonce-list.cpp @@ -32,17 +32,6 @@ namespace nfd { NFD_LOG_INIT(DeadNonceList); -const time::nanoseconds DeadNonceList::DEFAULT_LIFETIME; -const time::nanoseconds DeadNonceList::MIN_LIFETIME; -const size_t DeadNonceList::INITIAL_CAPACITY; -const size_t DeadNonceList::MIN_CAPACITY; -const size_t DeadNonceList::MAX_CAPACITY; -const DeadNonceList::Entry DeadNonceList::MARK; -const size_t DeadNonceList::EXPECTED_MARK_COUNT; -const double DeadNonceList::CAPACITY_UP; -const double DeadNonceList::CAPACITY_DOWN; -const size_t DeadNonceList::EVICT_LIMIT; - DeadNonceList::DeadNonceList(time::nanoseconds lifetime) : m_lifetime(lifetime) , m_capacity(INITIAL_CAPACITY) @@ -61,15 +50,15 @@ DeadNonceList::DeadNonceList(time::nanoseconds lifetime) m_adjustCapacityEvent = getScheduler().schedule(m_adjustCapacityInterval, [this] { adjustCapacity(); }); BOOST_ASSERT_MSG(DEFAULT_LIFETIME >= MIN_LIFETIME, "DEFAULT_LIFETIME is too small"); - static_assert(INITIAL_CAPACITY >= MIN_CAPACITY, "INITIAL_CAPACITY is too small"); - static_assert(INITIAL_CAPACITY <= MAX_CAPACITY, "INITIAL_CAPACITY is too large"); + static_assert(INITIAL_CAPACITY >= MIN_CAPACITY); + static_assert(INITIAL_CAPACITY <= MAX_CAPACITY); BOOST_ASSERT_MSG(static_cast(MIN_CAPACITY * CAPACITY_UP) > MIN_CAPACITY, "CAPACITY_UP must be able to increase from MIN_CAPACITY"); BOOST_ASSERT_MSG(static_cast(MAX_CAPACITY * CAPACITY_DOWN) < MAX_CAPACITY, "CAPACITY_DOWN must be able to decrease from MAX_CAPACITY"); BOOST_ASSERT_MSG(CAPACITY_UP > 1.0, "CAPACITY_UP must adjust up"); BOOST_ASSERT_MSG(CAPACITY_DOWN < 1.0, "CAPACITY_DOWN must adjust down"); - static_assert(EVICT_LIMIT >= 1, "EVICT_LIMIT must be at least 1"); + static_assert(EVICT_LIMIT >= 1); } size_t diff --git a/daemon/table/fib-entry.cpp b/daemon/table/fib-entry.cpp index ade4c9f9..71c2516a 100644 --- a/daemon/table/fib-entry.cpp +++ b/daemon/table/fib-entry.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -62,7 +62,7 @@ Entry::addOrUpdateNextHop(Face& face, uint64_t cost) it->setCost(cost); this->sortNextHops(); - return std::make_pair(it, isNew); + return {it, isNew}; } bool diff --git a/daemon/table/fib-entry.hpp b/daemon/table/fib-entry.hpp index 7460edac..facf2485 100644 --- a/daemon/table/fib-entry.hpp +++ b/daemon/table/fib-entry.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -48,7 +48,9 @@ class Fib; */ using NextHopList = std::vector; -/** \brief represents a FIB entry +/** + * \brief Represents an entry in the FIB. + * \sa Fib */ class Entry : noncopyable { @@ -115,8 +117,8 @@ private: name_tree::Entry* m_nameTreeEntry = nullptr; - friend class name_tree::Entry; - friend class Fib; + friend name_tree::Entry; + friend Fib; }; } // namespace fib diff --git a/daemon/table/fib.cpp b/daemon/table/fib.cpp index 99892e64..c6c8f2cf 100644 --- a/daemon/table/fib.cpp +++ b/daemon/table/fib.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -135,10 +135,7 @@ Fib::erase(const Entry& entry) void Fib::addOrUpdateNextHop(Entry& entry, Face& face, uint64_t cost) { - NextHopList::iterator it; - bool isNew; - std::tie(it, isNew) = entry.addOrUpdateNextHop(face, cost); - + auto [it, isNew] = entry.addOrUpdateNextHop(face, cost); if (isNew) this->afterNewNextHop(entry.getPrefix(), *it); } diff --git a/daemon/table/fib.hpp b/daemon/table/fib.hpp index a4b688f5..6073533d 100644 --- a/daemon/table/fib.hpp +++ b/daemon/table/fib.hpp @@ -36,6 +36,7 @@ namespace nfd { namespace measurements { class Entry; } // namespace measurements + namespace pit { class Entry; } // namespace pit diff --git a/daemon/table/measurements-entry.hpp b/daemon/table/measurements-entry.hpp index fa80327a..a70f6e08 100644 --- a/daemon/table/measurements-entry.hpp +++ b/daemon/table/measurements-entry.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -36,7 +36,11 @@ class Entry; namespace measurements { -/** \brief Represents a Measurements entry +class Measurements; + +/** + * \brief Represents an entry in the %Measurements table. + * \sa Measurements */ class Entry : public StrategyInfoHost, noncopyable { @@ -60,8 +64,8 @@ private: name_tree::Entry* m_nameTreeEntry = nullptr; - friend class Measurements; - friend class name_tree::Entry; + friend Measurements; + friend name_tree::Entry; }; } // namespace measurements diff --git a/daemon/table/pit-entry.hpp b/daemon/table/pit-entry.hpp index 9e4a3574..e088e708 100644 --- a/daemon/table/pit-entry.hpp +++ b/daemon/table/pit-entry.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -39,21 +39,26 @@ class Entry; namespace pit { -/** \brief An unordered collection of in-records +/** + * \brief An unordered collection of in-records */ -typedef std::list InRecordCollection; +using InRecordCollection = std::list; -/** \brief An unordered collection of out-records +/** + * \brief An unordered collection of out-records */ -typedef std::list OutRecordCollection; +using OutRecordCollection = std::list; -/** \brief An Interest table entry +/** + * \brief Represents an entry in the %Interest table (PIT). * - * An Interest table entry represents either a pending Interest or a recently satisfied Interest. - * Each entry contains a collection of in-records, a collection of out-records, - * and two timers used in forwarding pipelines. - * In addition, the entry, in-records, and out-records are subclasses of StrategyInfoHost, - * which allows forwarding strategy to store arbitrary information on them. + * An Interest table entry represents either a pending Interest or a recently satisfied Interest. + * Each entry contains a collection of in-records, a collection of out-records, + * and two timers used in forwarding pipelines. + * In addition, the entry, in-records, and out-records are subclasses of StrategyInfoHost, + * which allows forwarding strategy to store arbitrary information on them. + * + * \sa Pit */ class Entry : public StrategyInfoHost, noncopyable { @@ -238,7 +243,7 @@ private: name_tree::Entry* m_nameTreeEntry = nullptr; - friend class name_tree::Entry; + friend name_tree::Entry; }; } // namespace pit diff --git a/daemon/table/pit-face-record.cpp b/daemon/table/pit-face-record.cpp index 639f4248..4674b8ec 100644 --- a/daemon/table/pit-face-record.cpp +++ b/daemon/table/pit-face-record.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2020, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -29,7 +29,7 @@ namespace nfd { namespace pit { // Impose a maximum lifetime to prevent integer overflow when calculating m_expiry. -static const time::milliseconds MAX_LIFETIME{10_days}; +const time::milliseconds MAX_LIFETIME = 10_days; void FaceRecord::update(const Interest& interest) diff --git a/daemon/table/pit-iterator.hpp b/daemon/table/pit-iterator.hpp index 35e02c55..b788e3cd 100644 --- a/daemon/table/pit-iterator.hpp +++ b/daemon/table/pit-iterator.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2018, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -48,7 +48,7 @@ public: * \param iPitEntry make this iterator to dereference to the i-th PIT entry in name tree entry */ explicit - Iterator(const NameTree::const_iterator& ntIt = NameTree::const_iterator(), size_t iPitEntry = 0); + Iterator(const NameTree::const_iterator& ntIt = {}, size_t iPitEntry = 0); const Entry& operator*() const diff --git a/daemon/table/pit.hpp b/daemon/table/pit.hpp index c998a4da..b44dce8c 100644 --- a/daemon/table/pit.hpp +++ b/daemon/table/pit.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -99,7 +99,7 @@ public: deleteInOutRecords(Entry* entry, const Face& face); public: // enumeration - typedef Iterator const_iterator; + using const_iterator = Iterator; /** \return an iterator to the beginning * \note Iteration order is implementation-defined. diff --git a/daemon/table/strategy-choice-entry.hpp b/daemon/table/strategy-choice-entry.hpp index f64d3321..ac592341 100644 --- a/daemon/table/strategy-choice-entry.hpp +++ b/daemon/table/strategy-choice-entry.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -40,7 +40,9 @@ class Entry; namespace strategy_choice { -/** \brief Represents a Strategy Choice entry +/** + * \brief Represents an entry in the %Strategy %Choice table. + * \sa StrategyChoice */ class Entry : noncopyable { @@ -80,7 +82,7 @@ private: unique_ptr m_strategy; name_tree::Entry* m_nameTreeEntry = nullptr; - friend class name_tree::Entry; + friend name_tree::Entry; }; } // namespace strategy_choice diff --git a/tests/core/algorithm.t.cpp b/tests/core/algorithm.t.cpp index fb232389..89a60bad 100644 --- a/tests/core/algorithm.t.cpp +++ b/tests/core/algorithm.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -34,24 +34,22 @@ BOOST_AUTO_TEST_SUITE(TestAlgorithm) BOOST_AUTO_TEST_CASE(FindLastIf) { - std::vector vec{1, 2, 3, 4, 5, 6, 7, 8, 9}; + const std::vector vec{1, 2, 3, 4, 5, 6, 7, 8, 9}; int hit1 = 0; - std::vector::const_iterator found1 = find_last_if(vec.begin(), vec.end(), - [&hit1] (int n) -> bool { - ++hit1; - return n % 2 == 0; - }); + auto found1 = find_last_if(vec.begin(), vec.end(), [&hit1] (int n) -> bool { + ++hit1; + return n % 2 == 0; + }); BOOST_REQUIRE(found1 != vec.end()); BOOST_CHECK_EQUAL(*found1, 8); BOOST_CHECK_LE(hit1, vec.size()); int hit2 = 0; - std::vector::const_iterator found2 = find_last_if(vec.begin(), vec.end(), - [&hit2] (int n) -> bool { - ++hit2; - return n < 0; - }); + auto found2 = find_last_if(vec.begin(), vec.end(), [&hit2] (int n) -> bool { + ++hit2; + return n < 0; + }); BOOST_CHECK(found2 == vec.end()); BOOST_CHECK_LE(hit2, vec.size()); } diff --git a/tests/core/version.t.cpp b/tests/core/version.t.cpp index 6024f8cd..349dfffe 100644 --- a/tests/core/version.t.cpp +++ b/tests/core/version.t.cpp @@ -43,9 +43,9 @@ BOOST_AUTO_TEST_CASE(VersionNumber) NFD_VERSION_MINOR * 1000 + NFD_VERSION_PATCH); - static_assert(NFD_VERSION_MAJOR >= 22 && NFD_VERSION_MAJOR <= 100, ""); - static_assert(NFD_VERSION_MINOR >= 1 && NFD_VERSION_MINOR <= 12, ""); - static_assert(NFD_VERSION_PATCH < 1000, ""); + static_assert(NFD_VERSION_MAJOR >= 22 && NFD_VERSION_MAJOR <= 100); + static_assert(NFD_VERSION_MINOR >= 1 && NFD_VERSION_MINOR <= 12); + static_assert(NFD_VERSION_PATCH < 1000); } BOOST_AUTO_TEST_CASE(VersionString) diff --git a/tests/daemon/face/datagram-transport.t.cpp b/tests/daemon/face/datagram-transport.t.cpp index 6d41a1fe..631e3948 100644 --- a/tests/daemon/face/datagram-transport.t.cpp +++ b/tests/daemon/face/datagram-transport.t.cpp @@ -56,7 +56,7 @@ BOOST_FIXTURE_TEST_CASE_TEMPLATE(Send, T, DatagramTransportFixtures, T) std::vector readBuf(block1.size()); this->remoteRead(readBuf); - BOOST_CHECK_EQUAL_COLLECTIONS(readBuf.begin(), readBuf.end(), block1.begin(), block1.end()); + BOOST_TEST(readBuf == block1, boost::test_tools::per_element()); BOOST_CHECK_EQUAL(this->transport->getState(), TransportState::UP); } diff --git a/tests/daemon/face/generic-link-service.t.cpp b/tests/daemon/face/generic-link-service.t.cpp index 11aeeb84..e4f04252 100644 --- a/tests/daemon/face/generic-link-service.t.cpp +++ b/tests/daemon/face/generic-link-service.t.cpp @@ -229,8 +229,7 @@ BOOST_AUTO_TEST_CASE(ReceiveInterest) auto interest1 = makeInterest("/23Rd9hEiR"); lp::Packet lpPacket; - lpPacket.set(std::make_pair( - interest1->wireEncode().begin(), interest1->wireEncode().end())); + lpPacket.set({interest1->wireEncode().begin(), interest1->wireEncode().end()}); lpPacket.set(0); // force LpPacket encoding transport->receivePacket(lpPacket.wireEncode()); @@ -264,8 +263,7 @@ BOOST_AUTO_TEST_CASE(ReceiveData) auto data1 = makeData("/12345689"); lp::Packet lpPacket; - lpPacket.set(std::make_pair( - data1->wireEncode().begin(), data1->wireEncode().end())); + lpPacket.set({data1->wireEncode().begin(), data1->wireEncode().end()}); lpPacket.set(0); // force LpPacket encoding transport->receivePacket(lpPacket.wireEncode()); @@ -282,11 +280,11 @@ BOOST_AUTO_TEST_CASE(ReceiveNack) options.allowLocalFields = false; initialize(options); - lp::Nack nack1 = makeNack(*makeInterest("/localhost/test", false, std::nullopt, 323), - lp::NackReason::NO_ROUTE); + auto nack1 = makeNack(*makeInterest("/localhost/test", false, std::nullopt, 323), + lp::NackReason::NO_ROUTE); lp::Packet lpPacket; - lpPacket.set(std::make_pair( - nack1.getInterest().wireEncode().begin(), nack1.getInterest().wireEncode().end())); + lpPacket.set({nack1.getInterest().wireEncode().begin(), + nack1.getInterest().wireEncode().end()}); lpPacket.set(nack1.getHeader()); transport->receivePacket(lpPacket.wireEncode()); @@ -430,12 +428,9 @@ BOOST_AUTO_TEST_CASE(ReassembleFragments) // fragment the packet LpFragmenter fragmenter({}); - size_t mtu = 100; - bool isOk = false; - std::vector frags; - std::tie(isOk, frags) = fragmenter.fragmentPacket(packet, mtu); + auto [isOk, frags] = fragmenter.fragmentPacket(packet, 100); BOOST_REQUIRE(isOk); - BOOST_CHECK_GT(frags.size(), 1); + BOOST_TEST(frags.size() > 1); // receive the fragments for (ssize_t fragIndex = frags.size() - 1; fragIndex >= 0; --fragIndex) { @@ -970,11 +965,11 @@ BOOST_AUTO_TEST_CASE(ReceiveNextHopFaceIdDropNack) options.allowLocalFields = true; initialize(options); - lp::Nack nack = makeNack(*makeInterest("/localhost/test", false, std::nullopt, 123), - lp::NackReason::NO_ROUTE); + auto nack = makeNack(*makeInterest("/localhost/test", false, std::nullopt, 123), + lp::NackReason::NO_ROUTE); lp::Packet packet; - packet.set(std::make_pair( - nack.getInterest().wireEncode().begin(), nack.getInterest().wireEncode().end())); + packet.set({nack.getInterest().wireEncode().begin(), + nack.getInterest().wireEncode().end()}); packet.set(nack.getHeader()); packet.set(1000); @@ -1205,11 +1200,11 @@ BOOST_AUTO_TEST_CASE(ReceiveCongestionMarkData) BOOST_AUTO_TEST_CASE(ReceiveCongestionMarkNack) { - lp::Nack nack = makeNack(*makeInterest("/localhost/test", false, std::nullopt, 123), - lp::NackReason::NO_ROUTE); + auto nack = makeNack(*makeInterest("/localhost/test", false, std::nullopt, 123), + lp::NackReason::NO_ROUTE); lp::Packet packet; - packet.set(std::make_pair( - nack.getInterest().wireEncode().begin(), nack.getInterest().wireEncode().end())); + packet.set({nack.getInterest().wireEncode().begin(), + nack.getInterest().wireEncode().end()}); packet.set(nack.getHeader()); packet.set(1); @@ -1310,11 +1305,11 @@ BOOST_AUTO_TEST_CASE(ReceiveNonDiscoveryDropNack) options.allowSelfLearning = true; initialize(options); - lp::Nack nack = makeNack(*makeInterest("/localhost/test", false, std::nullopt, 123), - lp::NackReason::NO_ROUTE); + auto nack = makeNack(*makeInterest("/localhost/test", false, std::nullopt, 123), + lp::NackReason::NO_ROUTE); lp::Packet packet; - packet.set(std::make_pair( - nack.getInterest().wireEncode().begin(), nack.getInterest().wireEncode().end())); + packet.set({nack.getInterest().wireEncode().begin(), + nack.getInterest().wireEncode().end()}); packet.set(nack.getHeader()); packet.set(lp::EmptyValue{}); @@ -1418,11 +1413,11 @@ BOOST_AUTO_TEST_CASE(ReceivePrefixAnnouncementDropNack) options.allowSelfLearning = true; initialize(options); - lp::Nack nack = makeNack(*makeInterest("/localhost/test", false, std::nullopt, 123), - lp::NackReason::NO_ROUTE); + auto nack = makeNack(*makeInterest("/localhost/test", false, std::nullopt, 123), + lp::NackReason::NO_ROUTE); lp::Packet packet; - packet.set(std::make_pair( - nack.getInterest().wireEncode().begin(), nack.getInterest().wireEncode().end())); + packet.set({nack.getInterest().wireEncode().begin(), + nack.getInterest().wireEncode().end()}); packet.set(nack.getHeader()); auto pah = makePrefixAnnHeader("/local/ndn/prefix"); packet.set(pah); diff --git a/tests/daemon/face/lp-fragmenter.t.cpp b/tests/daemon/face/lp-fragmenter.t.cpp index 30eb8e90..8bd48c24 100644 --- a/tests/daemon/face/lp-fragmenter.t.cpp +++ b/tests/daemon/face/lp-fragmenter.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2020, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -52,9 +52,7 @@ BOOST_AUTO_TEST_CASE(SingleFragment) auto data = makeData("/test/data123"); packet.add({data->wireEncode().begin(), data->wireEncode().end()}); - bool isOk = false; - std::vector frags; - std::tie(isOk, frags) = fragmenter.fragmentPacket(packet, mtu); + auto [isOk, frags] = fragmenter.fragmentPacket(packet, mtu); BOOST_REQUIRE(isOk); BOOST_REQUIRE_EQUAL(frags.size(), 1); @@ -64,8 +62,7 @@ BOOST_AUTO_TEST_CASE(SingleFragment) BOOST_CHECK(!frags[0].has()); BOOST_CHECK_LE(frags[0].wireEncode().size(), mtu); - ndn::Buffer::const_iterator fragBegin, fragEnd; - std::tie(fragBegin, fragEnd) = frags[0].get(); + auto [fragBegin, fragEnd] = frags[0].get(); BOOST_CHECK_EQUAL_COLLECTIONS(data->wireEncode().begin(), data->wireEncode().end(), fragBegin, fragEnd); } @@ -80,9 +77,7 @@ BOOST_AUTO_TEST_CASE(MultipleFragments) auto data = makeData("/test/data123/123456789/987654321/123456789"); packet.add({data->wireEncode().begin(), data->wireEncode().end()}); - bool isOk = false; - std::vector frags; - std::tie(isOk, frags) = fragmenter.fragmentPacket(packet, mtu); + auto [isOk, frags] = fragmenter.fragmentPacket(packet, mtu); BOOST_REQUIRE(isOk); BOOST_REQUIRE_EQUAL(frags.size(), 5); @@ -93,8 +88,7 @@ BOOST_AUTO_TEST_CASE(MultipleFragments) BOOST_CHECK_EQUAL(frags[0].get(), 0); BOOST_CHECK_EQUAL(frags[0].get(), 5); BOOST_CHECK_LE(frags[0].wireEncode().size(), mtu); - ndn::Buffer::const_iterator frag0Begin, frag0End; - std::tie(frag0Begin, frag0End) = frags[0].get(); + auto [frag0Begin, frag0End] = frags[0].get(); BOOST_REQUIRE_LE(std::distance(frag0Begin, frag0End), reassembledPayload.size()); auto reassembledPos = std::copy(frag0Begin, frag0End, reassembledPayload.begin()); @@ -103,8 +97,7 @@ BOOST_AUTO_TEST_CASE(MultipleFragments) BOOST_CHECK_EQUAL(frags[1].get(), 1); BOOST_CHECK_EQUAL(frags[1].get(), 5); BOOST_CHECK_LE(frags[1].wireEncode().size(), mtu); - ndn::Buffer::const_iterator frag1Begin, frag1End; - std::tie(frag1Begin, frag1End) = frags[1].get(); + auto [frag1Begin, frag1End] = frags[1].get(); BOOST_REQUIRE_LE(std::distance(frag1Begin, frag1End), std::distance(reassembledPos, reassembledPayload.end())); reassembledPos = std::copy(frag1Begin, frag1End, reassembledPos); @@ -114,8 +107,7 @@ BOOST_AUTO_TEST_CASE(MultipleFragments) BOOST_CHECK_EQUAL(frags[2].get(), 2); BOOST_CHECK_EQUAL(frags[2].get(), 5); BOOST_CHECK_LE(frags[2].wireEncode().size(), mtu); - ndn::Buffer::const_iterator frag2Begin, frag2End; - std::tie(frag2Begin, frag2End) = frags[2].get(); + auto [frag2Begin, frag2End] = frags[2].get(); BOOST_REQUIRE_LE(std::distance(frag2Begin, frag2End), std::distance(reassembledPos, reassembledPayload.end())); reassembledPos = std::copy(frag2Begin, frag2End, reassembledPos); @@ -125,8 +117,7 @@ BOOST_AUTO_TEST_CASE(MultipleFragments) BOOST_CHECK_EQUAL(frags[3].get(), 3); BOOST_CHECK_EQUAL(frags[3].get(), 5); BOOST_CHECK_LE(frags[3].wireEncode().size(), mtu); - ndn::Buffer::const_iterator frag3Begin, frag3End; - std::tie(frag3Begin, frag3End) = frags[3].get(); + auto [frag3Begin, frag3End] = frags[3].get(); BOOST_REQUIRE_LE(std::distance(frag3Begin, frag3End), std::distance(reassembledPos, reassembledPayload.end())); reassembledPos = std::copy(frag3Begin, frag3End, reassembledPos); @@ -136,14 +127,12 @@ BOOST_AUTO_TEST_CASE(MultipleFragments) BOOST_CHECK_EQUAL(frags[4].get(), 4); BOOST_CHECK_EQUAL(frags[4].get(), 5); BOOST_CHECK_LE(frags[4].wireEncode().size(), mtu); - ndn::Buffer::const_iterator frag4Begin, frag4End; - std::tie(frag4Begin, frag4End) = frags[4].get(); + auto [frag4Begin, frag4End] = frags[4].get(); BOOST_REQUIRE_LE(std::distance(frag4Begin, frag4End), std::distance(reassembledPos, reassembledPayload.end())); std::copy(frag4Begin, frag4End, reassembledPos); - BOOST_CHECK_EQUAL_COLLECTIONS(data->wireEncode().begin(), data->wireEncode().end(), - reassembledPayload.begin(), reassembledPayload.end()); + BOOST_TEST(data->wireEncode() == reassembledPayload, boost::test_tools::per_element()); } BOOST_AUTO_TEST_CASE(MtuTooSmall) diff --git a/tests/daemon/face/lp-reliability.t.cpp b/tests/daemon/face/lp-reliability.t.cpp index 526708fd..0d891e02 100644 --- a/tests/daemon/face/lp-reliability.t.cpp +++ b/tests/daemon/face/lp-reliability.t.cpp @@ -140,8 +140,7 @@ public: getPktNum(const lp::Packet& pkt) { BOOST_REQUIRE(pkt.has()); - ndn::Buffer::const_iterator begin, end; - std::tie(begin, end) = pkt.get(); + auto [begin, end] = pkt.get(); if (std::distance(begin, end) < 4) { return 0; } diff --git a/tests/daemon/face/tcp-transport.t.cpp b/tests/daemon/face/tcp-transport.t.cpp index 1ad0b709..c01aaefa 100644 --- a/tests/daemon/face/tcp-transport.t.cpp +++ b/tests/daemon/face/tcp-transport.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -187,14 +187,14 @@ BOOST_FIXTURE_TEST_CASE_TEMPLATE(PermanentReconnectWithExponentialBackoff, T, Tc // measure retry intervals auto retryTime1 = time::steady_clock::now(); - auto expectedWait1 = TcpTransport::s_initialReconnectWait; + auto expectedWait1 = TcpTransport::INITIAL_RECONNECT_DELAY; BOOST_REQUIRE_EQUAL(this->limitedIo.run(2, expectedWait1 + 1_s), // add some slack LimitedIo::EXCEED_OPS); auto retryTime2 = time::steady_clock::now(); BOOST_CHECK_EQUAL(transportObserver->getState(), TransportState::DOWN); auto expectedWait2 = time::duration_cast(expectedWait1 * - TcpTransport::s_reconnectWaitMultiplier); + TcpTransport::RECONNECT_DELAY_MULTIPLIER); BOOST_REQUIRE_EQUAL(this->limitedIo.run(2, expectedWait2 + 1_s), // add some slack LimitedIo::EXCEED_OPS); auto retryTime3 = time::steady_clock::now(); @@ -210,7 +210,7 @@ BOOST_FIXTURE_TEST_CASE_TEMPLATE(PermanentReconnectWithExponentialBackoff, T, Tc this->startAccept(remoteEp); auto expectedWait3 = time::duration_cast(expectedWait2 * - TcpTransport::s_reconnectWaitMultiplier); + TcpTransport::RECONNECT_DELAY_MULTIPLIER); BOOST_REQUIRE_EQUAL(this->limitedIo.run(3, // reconnect, handleReconnect, async_accept expectedWait3 + 1_s), LimitedIo::EXCEED_OPS); BOOST_CHECK_EQUAL(transportObserver->getState(), TransportState::UP); diff --git a/tests/daemon/face/unicast-udp-transport.t.cpp b/tests/daemon/face/unicast-udp-transport.t.cpp index e5962dbc..24d47fd5 100644 --- a/tests/daemon/face/unicast-udp-transport.t.cpp +++ b/tests/daemon/face/unicast-udp-transport.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -162,7 +162,7 @@ BOOST_FIXTURE_TEST_CASE(RemoteClosePermanent, RemoteCloseFixture) }); BOOST_REQUIRE_EQUAL(limitedIo.run(1, 1_s), LimitedIo::EXCEED_OPS); - BOOST_CHECK_EQUAL_COLLECTIONS(readBuf.begin(), readBuf.end(), block1.begin(), block1.end()); + BOOST_TEST(readBuf == block1, boost::test_tools::per_element()); Block block2 = ndn::encoding::makeStringBlock(301, "world"); ndn::Buffer buf(block2.begin(), block2.end()); diff --git a/tests/daemon/fw/asf-strategy.t.cpp b/tests/daemon/fw/asf-strategy.t.cpp index f07e72aa..e80a2876 100644 --- a/tests/daemon/fw/asf-strategy.t.cpp +++ b/tests/daemon/fw/asf-strategy.t.cpp @@ -114,11 +114,9 @@ protected: shared_ptr consumer; shared_ptr producer; - static const Name PRODUCER_PREFIX; + static inline const Name PRODUCER_PREFIX{"/hr/C"}; }; -const Name AsfGridFixture::PRODUCER_PREFIX("/hr/C"); - class AsfStrategyParametersGridFixture : public AsfGridFixture { protected: diff --git a/tests/daemon/fw/strategy-nack-return.t.cpp b/tests/daemon/fw/strategy-nack-return.t.cpp index a091fb58..b928c929 100644 --- a/tests/daemon/fw/strategy-nack-return.t.cpp +++ b/tests/daemon/fw/strategy-nack-return.t.cpp @@ -274,26 +274,12 @@ BOOST_FIXTURE_TEST_CASE_TEMPLATE(LiveDeadlock, BOOST_CHECK_GT(nNacksD, 0); } -template +template struct NackReasonCombination { - static lp::NackReason - getX() - { - return X; - } - - static lp::NackReason - getY() - { - return Y; - } - - static lp::NackReason - getExpectedResult() - { - return R; - } + static constexpr lp::NackReason firstReason{X}; + static constexpr lp::NackReason secondReason{Y}; + static constexpr lp::NackReason expectedResult{R}; }; using NackReasonCombinations = boost::mpl::vector< @@ -320,24 +306,24 @@ BOOST_FIXTURE_TEST_CASE_TEMPLATE(CombineReasons, Combination, NackReasonCombinations, StrategyNackReturnFixture) { - fib::Entry& fibEntry = *fib.insert(Name()).first; + auto& fibEntry = *fib.insert(Name()).first; fib.addOrUpdateNextHop(fibEntry, *face3, 10); fib.addOrUpdateNextHop(fibEntry, *face4, 20); fib.addOrUpdateNextHop(fibEntry, *face5, 30); auto interest1 = makeInterest("/F6sEwB24I", false, std::nullopt, 282); - shared_ptr pitEntry = pit.insert(*interest1).first; + auto pitEntry = pit.insert(*interest1).first; pitEntry->insertOrUpdateInRecord(*face1, *interest1); pitEntry->insertOrUpdateOutRecord(*face3, *interest1); pitEntry->insertOrUpdateOutRecord(*face4, *interest1); - lp::Nack nack3 = makeNack(*interest1, Combination::getX()); + lp::Nack nack3 = makeNack(*interest1, Combination::firstReason); pitEntry->getOutRecord(*face3)->setIncomingNack(nack3); strategy.afterReceiveNack(nack3, FaceEndpoint(*face3, 0), pitEntry); BOOST_CHECK_EQUAL(strategy.sendNackHistory.size(), 0); - lp::Nack nack4 = makeNack(*interest1, Combination::getY()); + lp::Nack nack4 = makeNack(*interest1, Combination::secondReason); pitEntry->getOutRecord(*face4)->setIncomingNack(nack4); strategy.afterReceiveNack(nack4, FaceEndpoint(*face4, 0), pitEntry); @@ -345,7 +331,7 @@ BOOST_FIXTURE_TEST_CASE_TEMPLATE(CombineReasons, BOOST_CHECK_EQUAL(strategy.sendNackHistory[0].pitInterest.wireEncode(), pitEntry->getInterest().wireEncode()); BOOST_CHECK_EQUAL(strategy.sendNackHistory[0].outFaceId, face1->getId()); - BOOST_CHECK_EQUAL(strategy.sendNackHistory[0].header.getReason(), Combination::getExpectedResult()); + BOOST_CHECK_EQUAL(strategy.sendNackHistory[0].header.getReason(), Combination::expectedResult); } BOOST_AUTO_TEST_SUITE_END() // TestStrategyNackReturn diff --git a/tests/daemon/fw/strategy-tester.hpp b/tests/daemon/fw/strategy-tester.hpp index 03c2f77d..5391ddee 100644 --- a/tests/daemon/fw/strategy-tester.hpp +++ b/tests/daemon/fw/strategy-tester.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -91,7 +91,7 @@ public: ++nActions; }); - std::forward(f)(); + std::invoke(std::forward(f)); if (nActions < nExpectedActions) { // If strategy doesn't forward anything (e.g., decides not to forward an Interest), the number diff --git a/tests/daemon/fw/topology-tester.cpp b/tests/daemon/fw/topology-tester.cpp index 73f99997..c44d61df 100644 --- a/tests/daemon/fw/topology-tester.cpp +++ b/tests/daemon/fw/topology-tester.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2020, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -74,10 +74,7 @@ void TopologyLink::addFace(TopologyNode i, shared_ptr face) { auto receiveCb = [this, i] (const Block& packet) { transmit(i, packet); }; - - auto ret = m_transports.emplace(std::piecewise_construct, - std::forward_as_tuple(i), - std::forward_as_tuple(std::move(face), std::move(receiveCb))); + auto ret = m_transports.try_emplace(i, std::move(face), std::move(receiveCb)); BOOST_ASSERT(ret.second); auto& node = ret.first->second; @@ -93,12 +90,12 @@ TopologyLink::transmit(TopologyNode i, const Block& packet) const auto& blockedDestinations = m_transports.at(i).blockedDestinations; - for (const auto& p : m_transports) { - if (p.first == i || blockedDestinations.count(p.first) > 0) { + for (const auto& [node, transport] : m_transports) { + if (node == i || blockedDestinations.count(node) > 0) { continue; } - getScheduler().schedule(m_delay, [packet, recipient = p.second.transport] { + getScheduler().schedule(m_delay, [packet, recipient = transport.transport] { recipient->receivePacket(packet); }); } diff --git a/tests/daemon/fw/unsolicited-data-policy.t.cpp b/tests/daemon/fw/unsolicited-data-policy.t.cpp index 5c8c8add..77722c76 100644 --- a/tests/daemon/fw/unsolicited-data-policy.t.cpp +++ b/tests/daemon/fw/unsolicited-data-policy.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -95,8 +95,8 @@ template struct FaceScopePolicyTest { using PolicyType = Policy; - using ShouldAdmitLocal = std::integral_constant; - using ShouldAdmitNonLocal = std::integral_constant; + using ShouldAdmitLocal = std::bool_constant; + using ShouldAdmitNonLocal = std::bool_constant; }; using FaceScopePolicyTests = boost::mpl::vector< diff --git a/tests/daemon/limited-io.cpp b/tests/daemon/limited-io.cpp index aeb1ea7c..c7e9b1b9 100644 --- a/tests/daemon/limited-io.cpp +++ b/tests/daemon/limited-io.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -32,9 +32,6 @@ namespace nfd { namespace tests { -const int LimitedIo::UNLIMITED_OPS = std::numeric_limits::max(); -const time::nanoseconds LimitedIo::UNLIMITED_TIME = time::nanoseconds::min(); - LimitedIo::LimitedIo(GlobalIoTimeFixture* fixture) : m_fixture(fixture) { diff --git a/tests/daemon/limited-io.hpp b/tests/daemon/limited-io.hpp index a34d20ef..efa35c9b 100644 --- a/tests/daemon/limited-io.hpp +++ b/tests/daemon/limited-io.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -95,8 +95,8 @@ private: afterTimeout(); public: - static const int UNLIMITED_OPS; - static const time::nanoseconds UNLIMITED_TIME; + static constexpr int UNLIMITED_OPS = std::numeric_limits::max(); + static constexpr time::nanoseconds UNLIMITED_TIME = time::nanoseconds::min(); private: GlobalIoTimeFixture* m_fixture; diff --git a/tests/daemon/mgmt/fib-manager.t.cpp b/tests/daemon/mgmt/fib-manager.t.cpp index 61316700..544eda5d 100644 --- a/tests/daemon/mgmt/fib-manager.t.cpp +++ b/tests/daemon/mgmt/fib-manager.t.cpp @@ -438,8 +438,7 @@ BOOST_AUTO_TEST_CASE(FibDataset) } BOOST_CHECK_EQUAL(actualPrefixes.size(), 0); - BOOST_CHECK_EQUAL_COLLECTIONS(receivedRecords.begin(), receivedRecords.end(), - expectedRecords.begin(), expectedRecords.end()); + BOOST_TEST(receivedRecords == expectedRecords, boost::test_tools::per_element()); } BOOST_AUTO_TEST_SUITE_END() // List diff --git a/tests/daemon/mgmt/manager-common-fixture.cpp b/tests/daemon/mgmt/manager-common-fixture.cpp index 83136be4..3188ee44 100644 --- a/tests/daemon/mgmt/manager-common-fixture.cpp +++ b/tests/daemon/mgmt/manager-common-fixture.cpp @@ -28,8 +28,6 @@ namespace nfd { namespace tests { -const Name CommandInterestSignerFixture::DEFAULT_COMMAND_SIGNER_IDENTITY("/CommandInterestSignerFixture-identity"); - CommandInterestSignerFixture::CommandInterestSignerFixture() : m_signer(m_keyChain) { diff --git a/tests/daemon/mgmt/manager-common-fixture.hpp b/tests/daemon/mgmt/manager-common-fixture.hpp index e7171722..005d4567 100644 --- a/tests/daemon/mgmt/manager-common-fixture.hpp +++ b/tests/daemon/mgmt/manager-common-fixture.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -65,7 +65,7 @@ protected: const Name& identity = DEFAULT_COMMAND_SIGNER_IDENTITY); protected: - static const Name DEFAULT_COMMAND_SIGNER_IDENTITY; + static inline const Name DEFAULT_COMMAND_SIGNER_IDENTITY{"/CommandInterestSignerFixture-identity"}; private: ndn::security::InterestSigner m_signer; @@ -188,7 +188,7 @@ public: } }; -template +template class CommandFailure { public: diff --git a/tests/daemon/mgmt/rib-manager-sl-announce.t.cpp b/tests/daemon/mgmt/rib-manager-sl-announce.t.cpp index 4d156595..ebfe7d0d 100644 --- a/tests/daemon/mgmt/rib-manager-sl-announce.t.cpp +++ b/tests/daemon/mgmt/rib-manager-sl-announce.t.cpp @@ -274,7 +274,7 @@ BOOST_AUTO_TEST_CASE(AnnounceReplace) BOOST_AUTO_TEST_CASE(AnnounceExpired) { - auto pa = makeTrustedAnn("/awrVv6V7", 1_h, std::make_pair(-3_h, -1_h)); + auto pa = makeTrustedAnn("/awrVv6V7", 1_h, std::pair(-3_h, -1_h)); BOOST_CHECK_EQUAL(slAnnounceSync(pa, 9087, 1_h), SlAnnounceResult::EXPIRED); BOOST_CHECK(findAnnRoute("/awrVv6V7", 9087) == nullptr); diff --git a/tests/daemon/mgmt/rib-manager.t.cpp b/tests/daemon/mgmt/rib-manager.t.cpp index 682eb307..be4638f4 100644 --- a/tests/daemon/mgmt/rib-manager.t.cpp +++ b/tests/daemon/mgmt/rib-manager.t.cpp @@ -494,8 +494,7 @@ BOOST_FIXTURE_TEST_CASE(RibDataset, UnauthorizedRibManagerFixture) } BOOST_CHECK_EQUAL(actualPrefixes.size(), 0); - BOOST_CHECK_EQUAL_COLLECTIONS(receivedRecords.begin(), receivedRecords.end(), - expectedRecords.begin(), expectedRecords.end()); + BOOST_TEST(receivedRecords == expectedRecords, boost::test_tools::per_element()); } BOOST_FIXTURE_TEST_SUITE(FaceMonitor, LocalhostAuthorizedRibManagerFixture) diff --git a/tests/daemon/mgmt/strategy-choice-manager.t.cpp b/tests/daemon/mgmt/strategy-choice-manager.t.cpp index 7fdd8fa1..3e42d1c8 100644 --- a/tests/daemon/mgmt/strategy-choice-manager.t.cpp +++ b/tests/daemon/mgmt/strategy-choice-manager.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -62,12 +62,8 @@ public: Name getInstanceName(const Name& name) const { - bool hasEntry = false; - Name instanceName; - std::tie(hasEntry, instanceName) = sc.get(name); - return hasEntry ? - instanceName : - Name("/no-StrategyChoice-entry-at").append(name); + auto [hasEntry, instanceName] = sc.get(name); + return hasEntry ? instanceName : Name("/no-StrategyChoice-entry-at").append(name); } protected: diff --git a/tests/daemon/rib/readvertise/readvertise.t.cpp b/tests/daemon/rib/readvertise/readvertise.t.cpp index 8916c00c..ffcab716 100644 --- a/tests/daemon/rib/readvertise/readvertise.t.cpp +++ b/tests/daemon/rib/readvertise/readvertise.t.cpp @@ -220,11 +220,10 @@ BOOST_AUTO_TEST_CASE(DestinationAvailability) this->setDestinationAvailability(true); std::set advertisedPrefixes; boost::copy(destination->advertiseHistory | boost::adaptors::transformed( - [] (const DummyReadvertiseDestination::HistoryEntry& he) { return he.prefix; }), + [] (const auto& he) { return he.prefix; }), std::inserter(advertisedPrefixes, advertisedPrefixes.end())); - std::set expectedPrefixes{"/A", "/B"}; - BOOST_CHECK_EQUAL_COLLECTIONS(advertisedPrefixes.begin(), advertisedPrefixes.end(), - expectedPrefixes.begin(), expectedPrefixes.end()); + const std::set expectedPrefixes{"/A", "/B"}; + BOOST_TEST(advertisedPrefixes == expectedPrefixes, boost::test_tools::per_element()); destination->advertiseHistory.clear(); this->setDestinationAvailability(false); diff --git a/tests/daemon/rib/rib-update.t.cpp b/tests/daemon/rib/rib-update.t.cpp index 81ee10ee..90c80f05 100644 --- a/tests/daemon/rib/rib-update.t.cpp +++ b/tests/daemon/rib/rib-update.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -27,25 +27,20 @@ #include "rib/rib-update-batch.hpp" #include "tests/test-common.hpp" -#include "tests/daemon/global-io-fixture.hpp" #include "tests/daemon/rib/create-route.hpp" namespace nfd { namespace rib { namespace tests { -using namespace nfd::tests; - -BOOST_FIXTURE_TEST_SUITE(TestRibUpdate, GlobalIoFixture) +BOOST_AUTO_TEST_SUITE(TestRibUpdate) BOOST_AUTO_TEST_CASE(BatchBasic) { const uint64_t faceId = 1; - RibUpdateBatch batch(faceId); Route routeRegister = createRoute(faceId, 128, 10, ndn::nfd::ROUTE_FLAG_CHILD_INHERIT); - RibUpdate registerUpdate; registerUpdate.setAction(RibUpdate::REGISTER) .setName("/a") @@ -56,7 +51,6 @@ BOOST_AUTO_TEST_CASE(BatchBasic) BOOST_CHECK_EQUAL(batch.getFaceId(), faceId); Route routeUnregister = createRoute(faceId, 0, 0, ndn::nfd::ROUTE_FLAG_CAPTURE); - RibUpdate unregisterUpdate; unregisterUpdate.setAction(RibUpdate::UNREGISTER) .setName("/a/b") @@ -65,7 +59,7 @@ BOOST_AUTO_TEST_CASE(BatchBasic) batch.add(unregisterUpdate); BOOST_REQUIRE_EQUAL(batch.size(), 2); - RibUpdateBatch::const_iterator it = batch.begin(); + auto it = batch.begin(); BOOST_CHECK_EQUAL(it->getAction(), RibUpdate::REGISTER); BOOST_CHECK_EQUAL(it->getName(), "/a"); diff --git a/tests/daemon/table/cs.t.cpp b/tests/daemon/table/cs.t.cpp index 85886da3..b8e34de2 100644 --- a/tests/daemon/table/cs.t.cpp +++ b/tests/daemon/table/cs.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -264,12 +264,12 @@ BOOST_AUTO_TEST_CASE(Enumeration) insert(12, nameAB); insert(4, nameD); - std::set expected = {nameA, nameAB, nameABC, nameD}; + const std::set expected{nameA, nameAB, nameABC, nameD}; std::set actual; for (const auto& csEntry : cs) { actual.insert(csEntry.getName()); } - BOOST_CHECK_EQUAL_COLLECTIONS(actual.begin(), actual.end(), expected.begin(), expected.end()); + BOOST_TEST(actual == expected, boost::test_tools::per_element()); } BOOST_AUTO_TEST_SUITE_END() // TestCs diff --git a/tests/daemon/table/dead-nonce-list.t.cpp b/tests/daemon/table/dead-nonce-list.t.cpp index b4bcec90..44b0bfd2 100644 --- a/tests/daemon/table/dead-nonce-list.t.cpp +++ b/tests/daemon/table/dead-nonce-list.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -145,9 +145,6 @@ protected: scheduler::ScopedEventId addNonceEvent; }; -const time::nanoseconds PeriodicalInsertionFixture::LIFETIME; -const time::nanoseconds PeriodicalInsertionFixture::ADD_INTERVAL; - BOOST_FIXTURE_TEST_CASE(Lifetime, PeriodicalInsertionFixture) { BOOST_CHECK_EQUAL(dnl.getLifetime(), LIFETIME); diff --git a/tests/daemon/table/fib.t.cpp b/tests/daemon/table/fib.t.cpp index 101b3b94..1655fac6 100644 --- a/tests/daemon/table/fib.t.cpp +++ b/tests/daemon/table/fib.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -92,7 +92,7 @@ BOOST_AUTO_TEST_CASE(FibEntry) // [(face1,30), (face2,40)] BOOST_CHECK_EQUAL(entry.getNextHops().size(), 2); { - NextHopList::const_iterator it = entry.getNextHops().begin(); + auto it = entry.getNextHops().begin(); BOOST_REQUIRE(it != entry.getNextHops().end()); BOOST_CHECK_EQUAL(&it->getFace(), face1.get()); BOOST_CHECK_EQUAL(it->getCost(), 30); @@ -112,7 +112,7 @@ BOOST_AUTO_TEST_CASE(FibEntry) // [(face2,10), (face1,30)] BOOST_CHECK_EQUAL(entry.getNextHops().size(), 2); { - NextHopList::const_iterator it = entry.getNextHops().begin(); + auto it = entry.getNextHops().begin(); BOOST_REQUIRE(it != entry.getNextHops().end()); BOOST_CHECK_EQUAL(&it->getFace(), face2.get()); BOOST_CHECK_EQUAL(it->getCost(), 10); diff --git a/tests/daemon/table/name-tree.t.cpp b/tests/daemon/table/name-tree.t.cpp index 26498346..6c410aa4 100644 --- a/tests/daemon/table/name-tree.t.cpp +++ b/tests/daemon/table/name-tree.t.cpp @@ -56,6 +56,7 @@ BOOST_AUTO_TEST_CASE(ComputeHash) } BOOST_AUTO_TEST_SUITE(Hashtable) + using name_tree::Hashtable; BOOST_AUTO_TEST_CASE(Modifiers) @@ -256,7 +257,7 @@ BOOST_AUTO_TEST_CASE(TableEntries) npe.insertPitEntry(pit2); BOOST_CHECK_EQUAL(npe.getPitEntries().size(), 2); - pit::Entry* pit1ptr = pit1.get(); + auto* pit1ptr = pit1.get(); weak_ptr pit1weak(pit1); pit1.reset(); BOOST_CHECK_EQUAL(pit1weak.use_count(), 1); // npe is the sole owner of pit1 @@ -338,7 +339,6 @@ BOOST_AUTO_TEST_CASE(Basic) Entry* npe0 = nt.findExactMatch(name0); BOOST_CHECK(npe0 == nullptr); - // findLongestPrefixMatch Entry* temp = nullptr; @@ -493,12 +493,10 @@ protected: } protected: - static const size_t N_BUCKETS = 16; + static constexpr size_t N_BUCKETS = 16; NameTree nt; }; -const size_t EnumerationFixture::N_BUCKETS; - BOOST_FIXTURE_TEST_CASE(IteratorFullEnumerate, EnumerationFixture) { nt.lookup("/a/b/c"); @@ -556,7 +554,7 @@ BOOST_AUTO_TEST_CASE(OnlyA) // Accept "root" nameA only auto&& enumerable = nt.partialEnumerate("/a", [] (const Entry& entry) { - return std::make_pair(entry.getName() == "/a", true); + return std::pair(entry.getName() == "/a", true); }); EnumerationVerifier(enumerable) @@ -570,7 +568,7 @@ BOOST_AUTO_TEST_CASE(ExceptA) // Accept anything except "root" nameA auto&& enumerable = nt.partialEnumerate("/a", [] (const Entry& entry) { - return std::make_pair(entry.getName() != "/a", true); + return std::pair(entry.getName() != "/a", true); }); EnumerationVerifier(enumerable) @@ -586,7 +584,7 @@ BOOST_AUTO_TEST_CASE(NoNameANoSubTreeAB) // No NameA // No SubTree from NameAB auto&& enumerable = nt.partialEnumerate("/a", [] (const Entry& entry) { - return std::make_pair(entry.getName() != "/a", entry.getName() != "/a/b"); + return std::pair(entry.getName() != "/a", entry.getName() != "/a/b"); }); EnumerationVerifier(enumerable) @@ -604,7 +602,7 @@ BOOST_AUTO_TEST_CASE(NoNameANoSubTreeAC) // No NameA // No SubTree from NameAC auto&& enumerable = nt.partialEnumerate("/a", [] (const Entry& entry) { - return std::make_pair(entry.getName() != "/a", entry.getName() != "/a/c"); + return std::pair(entry.getName() != "/a", entry.getName() != "/a/c"); }); EnumerationVerifier(enumerable) @@ -621,7 +619,7 @@ BOOST_AUTO_TEST_CASE(NoSubTreeA) // No Subtree from NameA auto&& enumerable = nt.partialEnumerate("/a", [] (const Entry& entry) { - return std::make_pair(true, entry.getName() != "/a"); + return std::pair(true, entry.getName() != "/a"); }); EnumerationVerifier(enumerable) @@ -647,23 +645,20 @@ BOOST_AUTO_TEST_CASE(Example) nt.lookup("/E"); nt.lookup("/F"); - auto&& enumerable = nt.partialEnumerate("/A", - [] (const Entry& entry) { - bool visitEntry = false; - bool visitChildren = false; + auto&& enumerable = nt.partialEnumerate("/A", [] (const Entry& entry) { + bool visitEntry = false; + bool visitChildren = false; - Name name = entry.getName(); + const Name& name = entry.getName(); + if (name == "/" || name == "/A/B" || name == "/A/B/C" || name == "/A/D") { + visitEntry = true; + } + if (name == "/" || name == "/A" || name == "/F") { + visitChildren = true; + } - if (name == "/" || name == "/A/B" || name == "/A/B/C" || name == "/A/D") { - visitEntry = true; - } - - if (name == "/" || name == "/A" || name == "/F") { - visitChildren = true; - } - - return std::make_pair(visitEntry, visitChildren); - }); + return std::pair(visitEntry, visitChildren); + }); EnumerationVerifier(enumerable) .expect("/A/B") diff --git a/tests/daemon/table/pit.t.cpp b/tests/daemon/table/pit.t.cpp index 03438d4c..defa7682 100644 --- a/tests/daemon/table/pit.t.cpp +++ b/tests/daemon/table/pit.t.cpp @@ -336,9 +336,9 @@ BOOST_AUTO_TEST_CASE(Iterator) for (const auto& pitEntry : pit) { actual.insert(&pitEntry.getInterest()); } - std::set expected = {interestA.get(), interestABC1.get(), - interestABC2.get(), interestD.get()}; - BOOST_CHECK_EQUAL_COLLECTIONS(actual.begin(), actual.end(), expected.begin(), expected.end()); + const auto expected = std::set{interestA.get(), interestABC1.get(), + interestABC2.get(), interestD.get()}; + BOOST_TEST(actual == expected, boost::test_tools::per_element()); } BOOST_AUTO_TEST_SUITE_END() // TestPit diff --git a/tests/daemon/table/strategy-choice.t.cpp b/tests/daemon/table/strategy-choice.t.cpp index d99ff44a..ff6b754a 100644 --- a/tests/daemon/table/strategy-choice.t.cpp +++ b/tests/daemon/table/strategy-choice.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -48,9 +48,7 @@ protected: insertAndGet(const Name& prefix, const Name& instanceName) { BOOST_REQUIRE(sc.insert(prefix, instanceName)); - bool isFound; - Name foundName; - std::tie(isFound, foundName) = sc.get(prefix); + auto [isFound, foundName] = sc.get(prefix); BOOST_REQUIRE(isFound); return foundName; } diff --git a/tests/daemon/table/strategy-info-host.t.cpp b/tests/daemon/table/strategy-info-host.t.cpp index 2a3a33e0..e4323e42 100644 --- a/tests/daemon/table/strategy-info-host.t.cpp +++ b/tests/daemon/table/strategy-info-host.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -50,8 +50,7 @@ public: ++g_DummyStrategyInfo_count; } - virtual - ~DummyStrategyInfo() + ~DummyStrategyInfo() override { --g_DummyStrategyInfo_count; } @@ -85,19 +84,16 @@ BOOST_AUTO_TEST_CASE(Basic) { StrategyInfoHost host; g_DummyStrategyInfo_count = 0; - bool isNew = false; - DummyStrategyInfo* info = nullptr; - std::tie(info, isNew) = host.insertStrategyInfo(3503); + auto [info, isNew] = host.insertStrategyInfo(3503); BOOST_CHECK_EQUAL(isNew, true); BOOST_CHECK_EQUAL(g_DummyStrategyInfo_count, 1); BOOST_REQUIRE(info != nullptr); BOOST_CHECK_EQUAL(info->m_id, 3503); BOOST_CHECK_EQUAL(host.getStrategyInfo(), info); - DummyStrategyInfo* info2 = nullptr; - std::tie(info2, isNew) = host.insertStrategyInfo(1032); - BOOST_CHECK_EQUAL(isNew, false); + auto [info2, isNew2] = host.insertStrategyInfo(1032); + BOOST_CHECK_EQUAL(isNew2, false); BOOST_CHECK_EQUAL(g_DummyStrategyInfo_count, 1); BOOST_CHECK_EQUAL(info2, info); BOOST_CHECK_EQUAL(info->m_id, 3503); diff --git a/tests/other/face-benchmark.cpp b/tests/other/face-benchmark.cpp index 1ed21436..0b809c6b 100644 --- a/tests/other/face-benchmark.cpp +++ b/tests/other/face-benchmark.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -102,14 +102,14 @@ private: // find a matching right uri FaceUri uriR; - for (const auto& pair : m_faceUris) { - if (pair.first.getHost() == faceL->getRemoteUri().getHost() && - pair.first.getScheme() == faceL->getRemoteUri().getScheme()) { - uriR = pair.second; + for (const auto& [first, second] : m_faceUris) { + if (first.getHost() == faceL->getRemoteUri().getHost() && + first.getScheme() == faceL->getRemoteUri().getScheme()) { + uriR = second; } - else if (pair.second.getHost() == faceL->getRemoteUri().getHost() && - pair.second.getScheme() == faceL->getRemoteUri().getScheme()) { - uriR = pair.first; + else if (second.getHost() == faceL->getRemoteUri().getHost() && + second.getScheme() == faceL->getRemoteUri().getScheme()) { + uriR = first; } } @@ -124,17 +124,17 @@ private: auto port = boost::lexical_cast(uriR.getPort()); if (uriR.getScheme() == "tcp4") { m_tcpChannel.connect(tcp::Endpoint(addr, port), {}, - std::bind(&FaceBenchmark::onRightFaceCreated, this, faceL, _1), + std::bind(&FaceBenchmark::onRightFaceCreated, faceL, _1), std::bind(&FaceBenchmark::onFaceCreationFailed, _1, _2)); } else if (uriR.getScheme() == "udp4") { m_udpChannel.connect(udp::Endpoint(addr, port), {}, - std::bind(&FaceBenchmark::onRightFaceCreated, this, faceL, _1), + std::bind(&FaceBenchmark::onRightFaceCreated, faceL, _1), std::bind(&FaceBenchmark::onFaceCreationFailed, _1, _2)); } } - void + static void onRightFaceCreated(const shared_ptr& faceL, const shared_ptr& faceR) { std::clog << "Right face created: remote=" << faceR->getRemoteUri() @@ -147,18 +147,18 @@ private: static void tieFaces(const shared_ptr& face1, const shared_ptr& face2) { - face1->afterReceiveInterest.connect([face2] (const Interest& interest, const EndpointId&) { + face1->afterReceiveInterest.connect([face2] (const auto& interest, const EndpointId&) { face2->sendInterest(interest); }); - face1->afterReceiveData.connect([face2] (const Data& data, const EndpointId&) { + face1->afterReceiveData.connect([face2] (const auto& data, const EndpointId&) { face2->sendData(data); }); - face1->afterReceiveNack.connect([face2] (const ndn::lp::Nack& nack, const EndpointId&) { + face1->afterReceiveNack.connect([face2] (const auto& nack, const EndpointId&) { face2->sendNack(nack); }); } - static void + [[noreturn]] static void onFaceCreationFailed(uint32_t status, const std::string& reason) { NDN_THROW(std::runtime_error("Failed to create face: [" + to_string(status) + "] " + reason)); diff --git a/tests/tools/nfdc/command-definition.t.cpp b/tests/tools/nfdc/command-definition.t.cpp index 777a5540..7dbbbf66 100644 --- a/tests/tools/nfdc/command-definition.t.cpp +++ b/tests/tools/nfdc/command-definition.t.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2019, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -24,6 +24,7 @@ */ #include "nfdc/command-definition.hpp" +#include "nfdc/status-report.hpp" #include "tests/test-common.hpp" diff --git a/tests/tools/nfdc/execute-command-fixture.hpp b/tests/tools/nfdc/execute-command-fixture.hpp index 1acadd0a..103c50e6 100644 --- a/tests/tools/nfdc/execute-command-fixture.hpp +++ b/tests/tools/nfdc/execute-command-fixture.hpp @@ -51,15 +51,11 @@ protected: CommandParser parser; registerCommands(parser); - - std::string noun, verb; - CommandArguments ca; - ExecuteCommand execute; - std::tie(noun, verb, ca, execute) = parser.parse(args, ParseMode::ONE_SHOT); + auto [noun, verb, ca, exec] = parser.parse(args, ParseMode::ONE_SHOT); Controller controller(face, m_keyChain); ExecuteContext ctx{noun, verb, ca, 0, out, err, face, m_keyChain, controller}; - execute(ctx); + exec(ctx); exitCode = ctx.exitCode; } diff --git a/tools/ndn-autoconfig/main.cpp b/tools/ndn-autoconfig/main.cpp index ecfad813..afedc38c 100644 --- a/tools/ndn-autoconfig/main.cpp +++ b/tools/ndn-autoconfig/main.cpp @@ -46,9 +46,9 @@ namespace autoconfig { namespace po = boost::program_options; -const time::nanoseconds DAEMON_INITIAL_DELAY = 100_ms; -const time::nanoseconds DAEMON_UNCONDITIONAL_INTERVAL = 1_h; -const time::nanoseconds NETMON_DAMPEN_PERIOD = 5_s; +constexpr time::nanoseconds DAEMON_INITIAL_DELAY = 100_ms; +constexpr time::nanoseconds DAEMON_UNCONDITIONAL_INTERVAL = 1_h; +constexpr time::nanoseconds NETMON_DAMPEN_PERIOD = 5_s; static void usage(std::ostream& os, diff --git a/tools/ndn-autoconfig/multicast-discovery.cpp b/tools/ndn-autoconfig/multicast-discovery.cpp index 0a76b228..a9fbc88c 100644 --- a/tools/ndn-autoconfig/multicast-discovery.cpp +++ b/tools/ndn-autoconfig/multicast-discovery.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -36,9 +36,9 @@ namespace autoconfig { using nfd::ControlParameters; const Name HUB_DISCOVERY_PREFIX("/localhop/ndn-autoconf/hub"); -const uint64_t HUB_DISCOVERY_ROUTE_COST(1); -const time::milliseconds HUB_DISCOVERY_ROUTE_EXPIRATION = 30_s; -const time::milliseconds HUB_DISCOVERY_INTEREST_LIFETIME = 4_s; +constexpr uint64_t HUB_DISCOVERY_ROUTE_COST(1); +constexpr time::milliseconds HUB_DISCOVERY_ROUTE_EXPIRATION = 30_s; +constexpr time::milliseconds HUB_DISCOVERY_INTEREST_LIFETIME = 4_s; MulticastDiscovery::MulticastDiscovery(Face& face, nfd::Controller& controller) : m_face(face) diff --git a/tools/ndn-autoconfig/procedure.cpp b/tools/ndn-autoconfig/procedure.cpp index b0896ec6..cda39ad3 100644 --- a/tools/ndn-autoconfig/procedure.cpp +++ b/tools/ndn-autoconfig/procedure.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -36,10 +36,10 @@ namespace autoconfig { using nfd::ControlParameters; using nfd::ControlResponse; -const time::nanoseconds FACEURI_CANONIZE_TIMEOUT = 4_s; +constexpr time::nanoseconds FACEURI_CANONIZE_TIMEOUT = 4_s; const std::vector HUB_PREFIXES{"/", "/localhop/nfd"}; -const nfd::RouteOrigin HUB_ROUTE_ORIGIN = nfd::ROUTE_ORIGIN_AUTOCONF; -const uint64_t HUB_ROUTE_COST = 100; +constexpr nfd::RouteOrigin HUB_ROUTE_ORIGIN = nfd::ROUTE_ORIGIN_AUTOCONF; +constexpr uint64_t HUB_ROUTE_COST = 100; Procedure::Procedure(Face& face, KeyChain& keyChain) : m_face(face) diff --git a/tools/nfdc/command-arguments.hpp b/tools/nfdc/command-arguments.hpp index 6e096d69..2ab30f2c 100644 --- a/tools/nfdc/command-arguments.hpp +++ b/tools/nfdc/command-arguments.hpp @@ -27,7 +27,6 @@ #define NFD_TOOLS_NFDC_COMMAND_ARGUMENTS_HPP #include "core/common.hpp" -#include "status-report.hpp" #include @@ -43,14 +42,14 @@ using ndn::nfd::RouteOrigin; /** \brief contains named command arguments */ -class CommandArguments : public std::map +class CommandArguments : public std::map> { public: /** \return the argument value, or nullopt if the argument is omitted on command line */ template std::optional - getOptional(const std::string& key) const + getOptional(std::string_view key) const { auto i = find(key); return i == end() ? std::nullopt : std::make_optional(std::any_cast(i->second)); @@ -60,7 +59,7 @@ public: */ template T - get(const std::string& key, const T& defaultValue = T()) const + get(std::string_view key, const T& defaultValue = T()) const { return getOptional(key).value_or(defaultValue); } @@ -69,7 +68,7 @@ public: * \return the argument value, or boost::logic::indeterminate if the argument is omitted on command line */ boost::logic::tribool - getTribool(const std::string& key) const + getTribool(std::string_view key) const { auto value = getOptional(key); return value ? boost::logic::tribool(*value) : boost::logic::indeterminate; diff --git a/tools/nfdc/command-definition.cpp b/tools/nfdc/command-definition.cpp index 3c450e1c..7952e25e 100644 --- a/tools/nfdc/command-definition.cpp +++ b/tools/nfdc/command-definition.cpp @@ -24,6 +24,7 @@ */ #include "command-definition.hpp" +#include "status-report.hpp" #include @@ -93,7 +94,7 @@ getMetavarFromType(ArgValueType vt) NDN_CXX_UNREACHABLE; } -CommandDefinition::CommandDefinition(const std::string& noun, const std::string& verb) +CommandDefinition::CommandDefinition(std::string_view noun, std::string_view verb) : m_noun(noun) , m_verb(verb) { @@ -103,8 +104,8 @@ CommandDefinition::~CommandDefinition() = default; CommandDefinition& CommandDefinition::addArg(const std::string& name, ArgValueType valueType, - Required isRequired, Positional allowPositional, - const std::string& metavar) + Required isRequired, Positional allowPositional, + const std::string& metavar) { bool isNew = m_args.emplace(name, Arg{name, valueType, static_cast(isRequired), @@ -151,7 +152,7 @@ CommandDefinition::parse(const std::vector& tokens, size_t start) c const std::string& valueToken = tokens[++i]; NDN_LOG_TRACE(arg.name << " has value " << valueToken); try { - ca[arg.name] = this->parseValue(arg.valueType, valueToken); + ca[arg.name] = parseValue(arg.valueType, valueToken); } catch (const std::exception& e) { NDN_LOG_TRACE(valueToken << " cannot be parsed as " << arg.valueType); @@ -180,7 +181,7 @@ CommandDefinition::parse(const std::vector& tokens, size_t start) c } try { - ca[arg.name] = this->parseValue(arg.valueType, token); + ca[arg.name] = parseValue(arg.valueType, token); NDN_LOG_TRACE(token << " is parsed as value for " << arg.name); break; } @@ -207,7 +208,7 @@ CommandDefinition::parse(const std::vector& tokens, size_t start) c ++positionalArgIndex; } - for (const std::string& argName : m_requiredArgs) { + for (const auto& argName : m_requiredArgs) { if (ca.count(argName) == 0) { NDN_THROW(Error(argName + ": required argument is missing")); } @@ -241,7 +242,7 @@ parseFacePersistency(const std::string& s) } std::any -CommandDefinition::parseValue(ArgValueType valueType, const std::string& token) const +CommandDefinition::parseValue(ArgValueType valueType, const std::string& token) { switch (valueType) { case ArgValueType::NONE: diff --git a/tools/nfdc/command-definition.hpp b/tools/nfdc/command-definition.hpp index dc5afedb..8cd56d9a 100644 --- a/tools/nfdc/command-definition.hpp +++ b/tools/nfdc/command-definition.hpp @@ -122,7 +122,8 @@ enum class Positional { YES = true ///< argument can be specified as positional }; -/** \brief declares semantics of a command +/** + * \brief Defines a command */ class CommandDefinition { @@ -133,17 +134,17 @@ public: using std::invalid_argument::invalid_argument; }; - CommandDefinition(const std::string& noun, const std::string& verb); + CommandDefinition(std::string_view noun, std::string_view verb); ~CommandDefinition(); - const std::string + const std::string& getNoun() const { return m_noun; } - const std::string + const std::string& getVerb() const { return m_verb; @@ -162,7 +163,7 @@ public: // help * \param title one-line description, written in lower case */ CommandDefinition& - setTitle(const std::string& title) + setTitle(std::string_view title) { m_title = title; return *this; @@ -191,12 +192,12 @@ public: // arguments parse(const std::vector& tokens, size_t start = 0) const; private: - std::any - parseValue(ArgValueType valueType, const std::string& token) const; + static std::any + parseValue(ArgValueType valueType, const std::string& token); private: - std::string m_noun; - std::string m_verb; + const std::string m_noun; + const std::string m_verb; std::string m_title; struct Arg diff --git a/tools/nfdc/command-parser.cpp b/tools/nfdc/command-parser.cpp index 0d59de23..69bc26a1 100644 --- a/tools/nfdc/command-parser.cpp +++ b/tools/nfdc/command-parser.cpp @@ -94,7 +94,7 @@ CommandParser::addAlias(const std::string& noun, const std::string& verb, const } std::vector -CommandParser::listCommands(const std::string& noun, ParseMode mode) const +CommandParser::listCommands(std::string_view noun, ParseMode mode) const { std::vector results; for (auto i : m_commandOrder) { @@ -126,7 +126,7 @@ CommandParser::parse(const std::vector& tokens, ParseMode mode) con NDN_LOG_TRACE("found command noun=" << def.getNoun() << " verb=" << def.getVerb()); size_t nConsumed = std::min(2, tokens.size()); - return std::make_tuple(def.getNoun(), def.getVerb(), def.parse(tokens, nConsumed), i->second->execute); + return {def.getNoun(), def.getVerb(), def.parse(tokens, nConsumed), i->second->execute}; } } // namespace nfdc diff --git a/tools/nfdc/command-parser.hpp b/tools/nfdc/command-parser.hpp index e0e10b06..f03027b8 100644 --- a/tools/nfdc/command-parser.hpp +++ b/tools/nfdc/command-parser.hpp @@ -93,7 +93,7 @@ public: * \return commands in insertion order */ std::vector - listCommands(const std::string& noun, ParseMode mode) const; + listCommands(std::string_view noun, ParseMode mode) const; /** \brief parse a command line * \param tokens command line diff --git a/tools/nfdc/execute-command.hpp b/tools/nfdc/execute-command.hpp index 2d8a7168..0458fb1e 100644 --- a/tools/nfdc/execute-command.hpp +++ b/tools/nfdc/execute-command.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ -/** - * Copyright (c) 2014-2017, Regents of the University of California, +/* + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -27,6 +27,7 @@ #define NFD_TOOLS_NFDC_EXECUTE_COMMAND_HPP #include "command-arguments.hpp" + #include #include #include @@ -46,7 +47,8 @@ using ndn::nfd::ControlParameters; using ndn::nfd::ControlResponse; using ndn::nfd::Controller; -/** \brief context for command execution +/** + * \brief Context for command execution */ class ExecuteContext { @@ -72,8 +74,8 @@ public: makeDatasetFailureHandler(const std::string& datasetName); public: - const std::string& noun; - const std::string& verb; + std::string_view noun; + std::string_view verb; const CommandArguments& args; int exitCode; ///< program exit code @@ -82,13 +84,13 @@ public: Face& face; KeyChain& keyChain; - ///\todo validator Controller& controller; }; -/** \brief a function to execute a command +/** + * \brief A function to execute a command */ -using ExecuteCommand = std::function; +using ExecuteCommand = std::function; } // namespace nfdc } // namespace tools diff --git a/tools/nfdc/find-face.cpp b/tools/nfdc/find-face.cpp index 05e7eecc..2240433d 100644 --- a/tools/nfdc/find-face.cpp +++ b/tools/nfdc/find-face.cpp @@ -114,10 +114,7 @@ FindFace::canonize(const std::string& fieldName, const FaceUri& uri) return uri; } - std::optional result; - std::string error; - std::tie(result, error) = nfdc::canonize(m_ctx, uri); - + auto [result, error] = nfdc::canonize(m_ctx, uri); if (result) { // Canonization succeeded return result; diff --git a/tools/nfdc/format-helpers.cpp b/tools/nfdc/format-helpers.cpp index a207bf8d..63f24176 100644 --- a/tools/nfdc/format-helpers.cpp +++ b/tools/nfdc/format-helpers.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -128,14 +128,13 @@ operator<<(std::ostream& os, const Spaces& spaces) return os; } -Separator::Separator(const std::string& first, const std::string& subsequent) +Separator::Separator(std::string_view first, std::string_view subsequent) : m_first(first) , m_subsequent(subsequent) - , m_count(0) { } -Separator::Separator(const std::string& subsequent) +Separator::Separator(std::string_view subsequent) : Separator("", subsequent) { } @@ -152,7 +151,6 @@ operator<<(std::ostream& os, Separator& sep) ItemAttributes::ItemAttributes(bool wantMultiLine, int maxAttributeWidth) : m_wantMultiLine(wantMultiLine) , m_maxAttributeWidth(maxAttributeWidth) - , m_count(0) { } diff --git a/tools/nfdc/format-helpers.hpp b/tools/nfdc/format-helpers.hpp index 95f3310e..4140ae2d 100644 --- a/tools/nfdc/format-helpers.hpp +++ b/tools/nfdc/format-helpers.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -102,10 +102,10 @@ operator<<(std::ostream& os, const Spaces& spaces); class Separator : noncopyable { public: - Separator(const std::string& first, const std::string& subsequent); + Separator(std::string_view first, std::string_view subsequent); explicit - Separator(const std::string& subsequent); + Separator(std::string_view subsequent); int getCount() const @@ -114,9 +114,9 @@ public: } private: - std::string m_first; - std::string m_subsequent; - int m_count; + const std::string m_first; + const std::string m_subsequent; + int m_count = 0; friend std::ostream& operator<<(std::ostream& os, Separator& sep); }; @@ -166,9 +166,9 @@ public: end() const; private: - bool m_wantMultiLine; - int m_maxAttributeWidth; - int m_count; + const bool m_wantMultiLine; + const int m_maxAttributeWidth; + int m_count = 0; friend std::ostream& operator<<(std::ostream& os, const ItemAttributes::Attribute& attr); }; diff --git a/tools/nfdc/help.cpp b/tools/nfdc/help.cpp index 3642a919..052d16cb 100644 --- a/tools/nfdc/help.cpp +++ b/tools/nfdc/help.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -38,10 +38,10 @@ namespace nfdc { NDN_LOG_INIT(nfdc.Help); -const int LIST_COMMAND_NAME_COLUMN_WIDTH = 16; +constexpr int LIST_COMMAND_NAME_COLUMN_WIDTH = 16; void -helpList(std::ostream& os, const CommandParser& parser, ParseMode mode, const std::string& noun) +helpList(std::ostream& os, const CommandParser& parser, ParseMode mode, std::string_view noun) { os << "nfdc [-h|--help] [-V|--version] [-f|--batch ] [ []]\n\n"; if (noun.empty()) { @@ -70,7 +70,7 @@ helpList(std::ostream& os, const CommandParser& parser, ParseMode mode, const st static void helpCommand(const std::string& noun, const std::string& verb) { - std::string manpage = "nfdc-" + noun; + const std::string manpage = "nfdc-" + noun; ::execlp("man", "man", manpage.data(), nullptr); NDN_LOG_FATAL("Error opening man page for " << manpage << ": " << std::strerror(errno)); @@ -79,7 +79,7 @@ helpCommand(const std::string& noun, const std::string& verb) int help(std::ostream& os, const CommandParser& parser, std::vector args) { - const auto helpOpts = {"help", "--help", "-h"}; + const auto helpOpts = {"help"sv, "--help"sv, "-h"sv}; auto it = std::find_first_of(args.begin(), args.end(), helpOpts.begin(), helpOpts.end()); if (it == args.end()) return 2; diff --git a/tools/nfdc/help.hpp b/tools/nfdc/help.hpp index ccad7189..53d21d48 100644 --- a/tools/nfdc/help.hpp +++ b/tools/nfdc/help.hpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2018, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -40,7 +40,7 @@ namespace nfdc { */ void helpList(std::ostream& os, const CommandParser& parser, - ParseMode mode = ParseMode::ONE_SHOT, const std::string& noun = ""); + ParseMode mode = ParseMode::ONE_SHOT, std::string_view noun = ""); /** \brief tries to help the user, if requested on the command line * diff --git a/tools/nfdc/main.cpp b/tools/nfdc/main.cpp index ebe9d3c0..a9d9c6fa 100644 --- a/tools/nfdc/main.cpp +++ b/tools/nfdc/main.cpp @@ -1,6 +1,6 @@ /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* - * Copyright (c) 2014-2021, Regents of the University of California, + * Copyright (c) 2014-2022, Regents of the University of California, * Arizona Board of Regents, * Colorado State University, * University Pierre & Marie Curie, Sorbonne University, @@ -62,15 +62,14 @@ main(int argc, char** argv) auto processLine = [&parser] (const std::vector& line) -> Command { try { - Command cmd; - std::tie(cmd.noun, cmd.verb, cmd.ca, cmd.execute) = parser.parse(line, ParseMode::ONE_SHOT); - return cmd; + auto [noun, verb, ca, execute] = parser.parse(line, ParseMode::ONE_SHOT); + return {noun, verb, ca, execute}; } catch (const std::invalid_argument& e) { int ret = help(std::cout, parser, line); if (ret == 2) std::cerr << e.what() << std::endl; - return {"", "", {}, nullptr}; + return {}; } }; @@ -83,7 +82,7 @@ main(int argc, char** argv) return 2; } - auto processIstream = [&commands,&processLine] (std::istream& is, const std::string& inputFile) { + auto processIstream = [&commands, &processLine] (std::istream& is, const std::string& inputFile) { std::string line; size_t lineCounter = 0; while (std::getline(is, line)) { @@ -118,9 +117,8 @@ main(int argc, char** argv) } std::vector lineArgs; - std::copy_if(firstNonEmptyToken, tokenizer.end(), - std::back_inserter>(lineArgs), - [] (const std::string& t) { return !t.empty(); }); + std::copy_if(firstNonEmptyToken, tokenizer.end(), std::back_inserter(lineArgs), + [] (const auto& t) { return !t.empty(); }); auto cmd = processLine(lineArgs); if (cmd.noun.empty()) { diff --git a/tools/nfdc/rib-module.cpp b/tools/nfdc/rib-module.cpp index df980c47..5ed8553a 100644 --- a/tools/nfdc/rib-module.cpp +++ b/tools/nfdc/rib-module.cpp @@ -203,9 +203,7 @@ RibModule::add(ExecuteContext& ctx) return; } - std::optional canonized; - std::string error; - std::tie(canonized, error) = canonize(ctx, *faceUri); + auto [canonized, error] = canonize(ctx, *faceUri); if (!canonized) { // Canonization failed auto canonizationError = canonizeErrorHelper(*faceUri, error);