Browse Source

Convert to autos and ranged loops

Nils Maier 12 năm trước cách đây
mục cha
commit
8526ceeb45
77 tập tin đã thay đổi với 557 bổ sung751 xóa
  1. 11 16
      src/AdaptiveURISelector.cc
  2. 8 12
      src/AnnounceList.cc
  3. 1 1
      src/AppleTLSContext.cc
  4. 2 3
      src/AsyncNameResolver.cc
  5. 1 1
      src/BtBitfieldMessage.cc
  6. 9 14
      src/BtDependency.cc
  7. 1 1
      src/BtExtendedMessage.cc
  8. 1 1
      src/BtHandshakeMessage.cc
  9. 1 1
      src/BtKeepAliveMessage.cc
  10. 14 17
      src/BtLeecherStateChoke.cc
  11. 1 1
      src/BtPieceMessage.cc
  12. 1 1
      src/BtPortMessage.cc
  13. 2 2
      src/BtSeederStateChoke.cc
  14. 2 3
      src/BtSetup.cc
  15. 1 1
      src/ConsoleStatCalc.cc
  16. 7 8
      src/Context.cc
  17. 8 9
      src/CookieStorage.cc
  18. 2 4
      src/DHTAutoSaveCommand.cc
  19. 10 11
      src/DHTBucket.cc
  20. 16 16
      src/DHTBucketRefreshTask.cc
  21. 2 3
      src/DHTConnectionImpl.cc
  22. 2 2
      src/DHTMessageFactoryImpl.cc
  23. 3 4
      src/DHTPeerAnnounceEntry.cc
  24. 8 11
      src/DHTPeerAnnounceStorage.cc
  25. 2 2
      src/DHTTokenTracker.cc
  26. 7 10
      src/DNSCache.cc
  27. 3 4
      src/DNSCache.h
  28. 2 5
      src/DefaultBtAnnounce.cc
  29. 3 4
      src/DefaultBtRequestFactory.cc
  30. 9 7
      src/DefaultPeerStorage.cc
  31. 20 27
      src/DefaultPieceStorage.cc
  32. 7 10
      src/DownloadContext.cc
  33. 12 18
      src/DownloadEngine.cc
  34. 26 28
      src/FeedbackURISelector.cc
  35. 34 40
      src/FileEntry.cc
  36. 1 1
      src/GroupId.cc
  37. 4 5
      src/HandshakeExtensionMessage.cc
  38. 2 3
      src/HaveEraseCommand.cc
  39. 9 15
      src/HttpHeader.cc
  40. 12 15
      src/HttpRequest.cc
  41. 13 19
      src/HttpResponse.cc
  42. 11 13
      src/HttpResponseCommand.cc
  43. 1 1
      src/IndexBtMessage.cc
  44. 12 16
      src/LibuvEventPoll.cc
  45. 6 9
      src/MSEHandshake.cc
  46. 26 42
      src/MetalinkParserStateV3Impl.cc
  47. 43 61
      src/MetalinkParserStateV4Impl.cc
  48. 19 20
      src/OptionHandlerImpl.cc
  49. 17 22
      src/OptionParser.cc
  50. 1 1
      src/PeerConnection.cc
  51. 1 1
      src/Piece.cc
  52. 1 1
      src/PollEventPoll.cc
  53. 2 2
      src/PriorityPieceSelector.cc
  54. 1 1
      src/RangeBtMessage.cc
  55. 3 3
      src/RequestGroup.cc
  56. 27 39
      src/RequestGroupMan.cc
  57. 2 3
      src/RpcMethod.cc
  58. 12 17
      src/RpcMethodImpl.cc
  59. 2 3
      src/RpcMethodImpl.h
  60. 5 9
      src/SegmentMan.cc
  61. 2 6
      src/SelectEventPoll.cc
  62. 1 1
      src/SinkStreamFilter.cc
  63. 2 4
      src/SocketCore.cc
  64. 4 7
      src/StreamFileAllocationEntry.cc
  65. 3 5
      src/UDPTrackerClient.cc
  66. 3 5
      src/UTMetadataRequestTracker.cc
  67. 1 1
      src/UnknownLengthPieceStorage.cc
  68. 10 10
      src/ValueBaseStructParserStateMachine.cc
  69. 16 32
      src/XmlRpcRequestParserStateMachine.cc
  70. 1 1
      src/ZeroBtMessage.cc
  71. 28 40
      src/bittorrent_helper.cc
  72. 4 6
      src/bittorrent_helper.h
  73. 2 2
      src/option_processing.cc
  74. 2 3
      src/paramed_string.h
  75. 3 3
      src/prefs.cc
  76. 2 4
      src/util.cc
  77. 1 1
      src/wallclock.cc

+ 11 - 16
src/AdaptiveURISelector.cc

@@ -263,8 +263,7 @@ std::string AdaptiveURISelector::getMaxDownloadSpeedUri
 {
   int max = -1;
   std::string uri = A2STR::NIL;
-  for(std::deque<std::string>::const_iterator i = uris.begin(),
-        eoi = uris.end(); i != eoi; ++i) {
+  for(auto i = uris.begin(), eoi = uris.end(); i != eoi; ++i) {
     std::shared_ptr<ServerStat> ss = getServerStats(*i);
     if(!ss)
       continue;
@@ -285,8 +284,7 @@ std::deque<std::string> AdaptiveURISelector::getUrisBySpeed
 (const std::deque<std::string>& uris, int min) const
 {
   std::deque<std::string> bests;
-  for(std::deque<std::string>::const_iterator i = uris.begin(),
-        eoi = uris.end(); i != eoi; ++i) {
+  for(auto i = uris.begin(), eoi = uris.end(); i != eoi; ++i) {
     std::shared_ptr<ServerStat> ss = getServerStats(*i);
     if(!ss)
       continue;
@@ -302,7 +300,7 @@ std::string AdaptiveURISelector::selectRandomUri
 (const std::deque<std::string>& uris) const
 {
   int pos = SimpleRandomizer::getInstance()->getRandomNumber(uris.size());
-  std::deque<std::string>::const_iterator i = uris.begin();
+  auto i = uris.begin();
   i = i+pos;
   return *i;
 }
@@ -310,11 +308,10 @@ std::string AdaptiveURISelector::selectRandomUri
 std::string AdaptiveURISelector::getFirstNotTestedUri
 (const std::deque<std::string>& uris) const
 {
-  for(std::deque<std::string>::const_iterator i = uris.begin(),
-        eoi = uris.end(); i != eoi; ++i) {
-    std::shared_ptr<ServerStat> ss = getServerStats(*i);
+  for (const auto& i : uris) {
+    std::shared_ptr<ServerStat> ss = getServerStats(i);
     if(!ss)
-      return *i;
+      return i;
   }
   return A2STR::NIL;
 }
@@ -324,9 +321,8 @@ std::string AdaptiveURISelector::getFirstToTestUri
 {
   int counter;
   int power;
-  for(std::deque<std::string>::const_iterator i = uris.begin(),
-        eoi = uris.end(); i != eoi; ++i) {
-    std::shared_ptr<ServerStat> ss = getServerStats(*i);
+  for (const auto& u : uris) {
+    std::shared_ptr<ServerStat> ss = getServerStats(u);
     if(!ss)
       continue;
     counter = ss->getCounter();
@@ -336,7 +332,7 @@ std::string AdaptiveURISelector::getFirstToTestUri
     /* We test the mirror another time if it has not been
      * tested since 2^counter days */
     if(ss->getLastUpdated().difference() > power*24*60*60) {
-      return *i;
+      return u;
     }
   }
   return A2STR::NIL;
@@ -359,9 +355,8 @@ int AdaptiveURISelector::getNbTestedServers
 (const std::deque<std::string>& uris) const
 {
   int counter = 0;
-  for(std::deque<std::string>::const_iterator i = uris.begin(),
-        eoi = uris.end(); i != eoi; ++i) {
-    std::shared_ptr<ServerStat> ss = getServerStats(*i);
+  for(const auto& u : uris) {
+    std::shared_ptr<ServerStat> ss = getServerStats(u);
     if(!ss)
       ++counter;
   }

+ 8 - 12
src/AnnounceList.cc

@@ -61,12 +61,11 @@ AnnounceList::~AnnounceList() {}
 void AnnounceList::reconfigure
 (const std::vector<std::vector<std::string> >& announceList)
 {
-  for(std::vector<std::vector<std::string> >::const_iterator itr =
-        announceList.begin(), eoi = announceList.end(); itr != eoi; ++itr) {
-    if((*itr).empty()) {
+  for (const auto& vec: announceList) {
+    if(vec.empty()) {
       continue;
     }
-    std::deque<std::string> urls((*itr).begin(), (*itr).end());
+    std::deque<std::string> urls(vec.begin(), vec.end());
     std::shared_ptr<AnnounceTier> tier(new AnnounceTier(urls));
     tiers_.push_back(tier);
   }
@@ -207,15 +206,13 @@ void AnnounceList::setCurrentTier
 }
 
 void AnnounceList::moveToStoppedAllowedTier() {
-  std::deque<std::shared_ptr<AnnounceTier> >::iterator itr =
-    find_wrap_if(tiers_.begin(), tiers_.end(),
-                 currentTier_,
-                 FindStoppedAllowedTier());
+  auto itr = find_wrap_if(tiers_.begin(), tiers_.end(), currentTier_,
+                          FindStoppedAllowedTier());
   setCurrentTier(itr);
 }
 
 void AnnounceList::moveToCompletedAllowedTier() {
-  std::deque<std::shared_ptr<AnnounceTier> >::iterator itr =
+  auto itr =
     find_wrap_if(tiers_.begin(), tiers_.end(),
                  currentTier_,
                  FindCompletedAllowedTier());
@@ -223,9 +220,8 @@ void AnnounceList::moveToCompletedAllowedTier() {
 }
 
 void AnnounceList::shuffle() {
-  for(std::deque<std::shared_ptr<AnnounceTier> >::const_iterator itr =
-        tiers_.begin(), eoi = tiers_.end(); itr != eoi; ++itr) {
-    std::deque<std::string>& urls = (*itr)->urls;
+  for (const auto& tier: tiers_) {
+    auto& urls = tier->urls;
     std::random_shuffle(urls.begin(), urls.end(),
                         *SimpleRandomizer::getInstance());
   }

+ 1 - 1
src/AppleTLSContext.cc

@@ -105,7 +105,7 @@ namespace {
     CFStringRef cerr = SecCopyErrorMessageString(err, nullptr);
     if (cerr) {
       size_t len = CFStringGetLength(cerr) * 4;
-      char *buf = new char[len];
+      auto buf = new char[len];
       if (CFStringGetCString(cerr, buf, len, kCFStringEncodingUTF8)) {
         rv = buf;
       }

+ 2 - 3
src/AsyncNameResolver.cc

@@ -151,12 +151,11 @@ ares_addr_node* parseAsyncDNSServers(const std::string& serversOpt)
   root.next = nullptr;
   ares_addr_node* tail = &root;
   ares_addr_node* node = nullptr;
-  for(std::vector<std::string>::const_iterator i = servers.begin(),
-        eoi = servers.end(); i != eoi; ++i) {
+  for (const auto& s: servers) {
     if(node == nullptr) {
       node = new ares_addr_node();
     }
-    size_t len = net::getBinAddr(&node->addr, (*i).c_str());
+    size_t len = net::getBinAddr(&node->addr, s.c_str());
     if(len != 0) {
       node->next = nullptr;
       node->family = (len == 4 ? AF_INET : AF_INET6);

+ 1 - 1
src/BtBitfieldMessage.cc

@@ -108,7 +108,7 @@ unsigned char* BtBitfieldMessage::createMessage() {
    * total: 5+bitfieldLength bytes
    */
   const size_t msgLength = 5+bitfieldLength_;
-  unsigned char* msg = new unsigned char[msgLength];
+  auto msg = new unsigned char[msgLength];
   bittorrent::createPeerMessageString(msg, msgLength, 1+bitfieldLength_, ID);
   memcpy(msg+5, bitfield_, bitfieldLength_);
   return msg;

+ 9 - 14
src/BtDependency.cc

@@ -128,28 +128,23 @@ bool BtDependency::resolve()
       } else {
         std::vector<std::shared_ptr<FileEntry> > destFiles;
         destFiles.reserve(fileEntries.size());
-        for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
-              fileEntries.begin(), eoi = fileEntries.end(); i != eoi; ++i) {
-          (*i)->setRequested(false);
-          destFiles.push_back(*i);
+        for(auto & e : fileEntries) {
+          e->setRequested(false);
+          destFiles.push_back(e);
         }
         std::sort(destFiles.begin(), destFiles.end(), EntryCmp());
         // Copy file path in dependant_'s FileEntries to newly created
         // context's FileEntries to endorse the path structure of
         // dependant_.  URIs and singleHostMultiConnection are also copied.
-        for(std::vector<std::shared_ptr<FileEntry> >::const_iterator s =
-              dependantFileEntries.begin(), eoi = dependantFileEntries.end();
-            s != eoi; ++s){
-          std::vector<std::shared_ptr<FileEntry> >::const_iterator d =
-            std::lower_bound(destFiles.begin(), destFiles.end(), *s,
-                             EntryCmp());
+        for(const auto& e: dependantFileEntries){
+          const auto d = std::lower_bound(destFiles.begin(), destFiles.end(), e,
+                                          EntryCmp());
           if(d == destFiles.end() ||
-             (*d)->getOriginalName() != (*s)->getOriginalName()) {
+             (*d)->getOriginalName() != e->getOriginalName()) {
             throw DL_ABORT_EX
-              (fmt("No entry %s in torrent file",
-                   (*s)->getOriginalName().c_str()));
+              (fmt("No entry %s in torrent file", e->getOriginalName().c_str()));
           } else {
-            copyValues(*d, *s);
+            copyValues(*d, e);
           }
         }
       }

+ 1 - 1
src/BtExtendedMessage.cc

@@ -68,7 +68,7 @@ unsigned char* BtExtendedMessage::createMessage()
    */
   std::string payload = extensionMessage_->getPayload();
   msgLength_ = 6+payload.size();
-  unsigned char* msg = new unsigned char[msgLength_];
+  auto msg = new unsigned char[msgLength_];
   bittorrent::createPeerMessageString(msg, msgLength_, 2+payload.size(), ID);
   *(msg+5) = extensionMessage_->getExtensionMessageID();
   memcpy(msg+6, payload.data(), payload.size());

+ 1 - 1
src/BtHandshakeMessage.cc

@@ -89,7 +89,7 @@ BtHandshakeMessage::create(const unsigned char* data, size_t dataLength)
 
 unsigned char* BtHandshakeMessage::createMessage()
 {
-  unsigned char* msg = new unsigned char[MESSAGE_LENGTH];
+  auto msg = new unsigned char[MESSAGE_LENGTH];
   msg[0] = pstrlen_;
   memcpy(msg+1, pstr_, PSTR_LENGTH);
   memcpy(msg+20, reserved_, RESERVED_LENGTH);

+ 1 - 1
src/BtKeepAliveMessage.cc

@@ -45,7 +45,7 @@ unsigned char* BtKeepAliveMessage::createMessage()
    * len --- 0, 4bytes
    * total: 4bytes
    */
-  unsigned char* msg = new unsigned char[MESSAGE_LENGTH];
+  auto msg = new unsigned char[MESSAGE_LENGTH];
   memset(msg, 0, MESSAGE_LENGTH);
   return msg;
 }

+ 14 - 17
src/BtLeecherStateChoke.cc

@@ -146,9 +146,8 @@ void BtLeecherStateChoke::plannedOptimisticUnchoke
   std::for_each(peerEntries.begin(), peerEntries.end(),
                 std::mem_fn(&PeerEntry::disableOptUnchoking));
 
-  std::vector<PeerEntry>::iterator i =
-    std::partition(peerEntries.begin(), peerEntries.end(),
-                   PeerFilter(true, true));
+  auto i = std::partition(peerEntries.begin(), peerEntries.end(),
+                          PeerFilter(true, true));
   if(i != peerEntries.begin()) {
     std::random_shuffle(peerEntries.begin(), i,
                         *SimpleRandomizer::getInstance());
@@ -160,9 +159,8 @@ void BtLeecherStateChoke::plannedOptimisticUnchoke
 
 void BtLeecherStateChoke::regularUnchoke(std::vector<PeerEntry>& peerEntries)
 {
-  std::vector<PeerEntry>::iterator rest =
-    std::partition(peerEntries.begin(), peerEntries.end(),
-                   std::mem_fn(&PeerEntry::isRegularUnchoker));
+  auto rest = std::partition(peerEntries.begin(), peerEntries.end(),
+                             std::mem_fn(&PeerEntry::isRegularUnchoker));
 
   std::sort(peerEntries.begin(), rest);
 
@@ -170,29 +168,28 @@ void BtLeecherStateChoke::regularUnchoke(std::vector<PeerEntry>& peerEntries)
   int count = 3;
 
   bool fastOptUnchoker = false;
-  std::vector<PeerEntry>::iterator peerIter = peerEntries.begin();
+  auto peerIter = peerEntries.begin();
   for(;peerIter != rest && count; ++peerIter, --count) {
-    (*peerIter).disableChokingRequired();
+    peerIter->disableChokingRequired();
     A2_LOG_INFO(fmt("RU: %s, dlspd=%d",
                     (*peerIter).getPeer()->getIPAddress().c_str(),
                     (*peerIter).getDownloadSpeed()));
-    if((*peerIter).getPeer()->optUnchoking()) {
+    if(peerIter->getPeer()->optUnchoking()) {
       fastOptUnchoker = true;
-      (*peerIter).disableOptUnchoking();
+      peerIter->disableOptUnchoking();
     }
   }
   if(fastOptUnchoker) {
     std::random_shuffle(peerIter, peerEntries.end(),
                         *SimpleRandomizer::getInstance());
-    for(std::vector<PeerEntry>::iterator i = peerIter,
-          eoi = peerEntries.end(); i != eoi; ++i) {
-      if((*i).getPeer()->peerInterested()) {
-        (*i).enableOptUnchoking();
-        A2_LOG_INFO(fmt("OU: %s", (*i).getPeer()->getIPAddress().c_str()));
+    for (auto& p : peerEntries) {
+      if(p.getPeer()->peerInterested()) {
+        p.enableOptUnchoking();
+        A2_LOG_INFO(fmt("OU: %s", p.getPeer()->getIPAddress().c_str()));
         break;
       } else {
-        (*i).disableChokingRequired();
-        A2_LOG_INFO(fmt("OU: %s", (*i).getPeer()->getIPAddress().c_str()));
+        p.disableChokingRequired();
+        A2_LOG_INFO(fmt("OU: %s", p.getPeer()->getIPAddress().c_str()));
       }
     }
   }

+ 1 - 1
src/BtPieceMessage.cc

@@ -125,7 +125,7 @@ void BtPieceMessage::doReceivedAction()
     if(piece->getWrDiskCacheEntry()) {
       // Write Disk Cache enabled. Unfortunately, it incurs extra data
       // copy.
-      unsigned char* dataCopy = new unsigned char[blockLength_];
+      auto dataCopy = new unsigned char[blockLength_];
       memcpy(dataCopy, data_+9, blockLength_);
       piece->updateWrCache(getPieceStorage()->getWrDiskCache(),
                            dataCopy, 0, blockLength_, blockLength_, offset);

+ 1 - 1
src/BtPortMessage.cc

@@ -106,7 +106,7 @@ unsigned char* BtPortMessage::createMessage()
    * port --- port number, 2bytes
    * total: 7bytes
    */
-  unsigned char* msg = new unsigned char[MESSAGE_LENGTH];
+  auto msg = new unsigned char[MESSAGE_LENGTH];
   bittorrent::createPeerMessageString(msg, MESSAGE_LENGTH, 3, ID);
   bittorrent::setShortIntParam(&msg[5], port_);
   return msg;

+ 2 - 2
src/BtSeederStateChoke.cc

@@ -124,8 +124,8 @@ void BtSeederStateChoke::unchoke
 
   std::sort(peers.begin(), peers.end());
 
-  std::vector<PeerEntry>::iterator r = peers.begin();
-  for(std::vector<PeerEntry>::iterator eoi = peers.end();
+  auto r = peers.begin();
+  for(auto eoi = peers.end();
       r != eoi && count; ++r, --count) {
     (*r).getPeer()->chokingRequired(false);
     A2_LOG_INFO(fmt("RU: %s, ulspd=%d",

+ 2 - 3
src/BtSetup.cc

@@ -229,10 +229,9 @@ void BtSetup::setup(std::vector<std::unique_ptr<Command>>& commands,
       } else {
         std::vector<std::pair<sockaddr_union, socklen_t> > ifAddrs;
         getInterfaceAddress(ifAddrs, lpdInterface, AF_INET, AI_NUMERICHOST);
-        for(std::vector<std::pair<sockaddr_union, socklen_t> >::const_iterator
-              i = ifAddrs.begin(), eoi = ifAddrs.end(); i != eoi; ++i) {
+        for (const auto& i : ifAddrs) {
           char host[NI_MAXHOST];
-          if(inetNtop(AF_INET, &(*i).first.in.sin_addr, host,
+          if(inetNtop(AF_INET, &i.first.in.sin_addr, host,
                       sizeof(host)) == 0 &&
              receiver->init(host)) {
             initialized = true;

+ 1 - 1
src/ConsoleStatCalc.cc

@@ -142,7 +142,7 @@ void printProgressCompact(std::ostream& o, const DownloadEngine* e,
     e->getRequestGroupMan()->getRequestGroups();
   size_t cnt = 0;
   const size_t MAX_ITEM = 5;
-  for(RequestGroupList::const_iterator i = groups.begin(),
+  for(auto i = groups.begin(),
         eoi = groups.end(); i != eoi && cnt < MAX_ITEM; ++i, ++cnt) {
     const std::shared_ptr<RequestGroup>& rg = *i;
     TransferStat stat = rg->calculateStat();

+ 7 - 8
src/Context.cc

@@ -115,20 +115,19 @@ void showFiles
 (const std::vector<std::string>& uris, const std::shared_ptr<Option>& op)
 {
   ProtocolDetector dt;
-  for(std::vector<std::string>::const_iterator i = uris.begin(),
-        eoi = uris.end(); i != eoi; ++i) {
+  for(const auto & uri : uris) {
     printf(">>> ");
-    printf(MSG_SHOW_FILES, (*i).c_str());
+    printf(MSG_SHOW_FILES, (uri).c_str());
     printf("\n");
     try {
 #ifdef ENABLE_BITTORRENT
-      if(dt.guessTorrentFile(*i)) {
-        showTorrentFile(*i);
+      if(dt.guessTorrentFile(uri)) {
+        showTorrentFile(uri);
       } else
 #endif // ENABLE_BITTORRENT
 #ifdef ENABLE_METALINK
-        if(dt.guessMetalinkFile(*i)) {
-          showMetalinkFile(*i, op);
+        if(dt.guessMetalinkFile(uri)) {
+          showMetalinkFile(uri, op);
         } else
 #endif // ENABLE_METALINK
           {
@@ -235,7 +234,7 @@ Context::Context(bool standalone,
   // command-line. If they are left, because op is used as a template
   // for new RequestGroup(such as created in RPC command), they causes
   // unintentional effect.
-  for(std::shared_ptr<Option> i = op; i; i = i->getParent()) {
+  for(auto i = op; i; i = i->getParent()) {
     i->remove(PREF_OUT);
     i->remove(PREF_FORCE_SEQUENTIAL);
     i->remove(PREF_INPUT_FILE);

+ 8 - 9
src/CookieStorage.cc

@@ -434,18 +434,17 @@ std::vector<const Cookie*> CookieStorage::criteriaFind
   }
   auto labels = splitDomainLabel(requestHost);
   auto node = rootNode_.get();
-  for(auto i = labels.rbegin(), eoi = labels.rend(); i != eoi; ++i) {
+  for (auto i = labels.rbegin(), eoi = labels.rend(); i != eoi; ++i) {
     auto nextNode = node->findNext(*i);
-    if(nextNode) {
-      nextNode->setLastAccessTime(now);
-      if(nextNode->getInLru()) {
-        updateLru(nextNode, now);
-      }
-      nextNode->findCookie(res, requestHost, requestPath, now, secure);
-      node = nextNode;
-    } else {
+    if(!nextNode) {
       break;
     }
+    nextNode->setLastAccessTime(now);
+    if(nextNode->getInLru()) {
+      updateLru(nextNode, now);
+    }
+    nextNode->findCookie(res, requestHost, requestPath, now, secure);
+    node = nextNode;
   }
   auto divs = std::vector<CookiePathDivider>{};
   std::transform(std::begin(res), std::end(res), std::back_inserter(divs),

+ 2 - 4
src/DHTAutoSaveCommand.cc

@@ -97,11 +97,9 @@ void DHTAutoSaveCommand::save()
   std::vector<std::shared_ptr<DHTNode> > nodes;
   std::vector<std::shared_ptr<DHTBucket> > buckets;
   routingTable_->getBuckets(buckets);
-  for(std::vector<std::shared_ptr<DHTBucket> >::const_iterator i = buckets.begin(),
-        eoi = buckets.end(); i != eoi; ++i) {
-    const std::shared_ptr<DHTBucket>& bucket = *i;
+  for (const auto& b : buckets) {
     std::vector<std::shared_ptr<DHTNode> > goodNodes;
-    bucket->getGoodNodes(goodNodes);
+    b->getGoodNodes(goodNodes);
     nodes.insert(nodes.end(), goodNodes.begin(), goodNodes.end());
   }
 

+ 10 - 11
src/DHTBucket.cc

@@ -110,7 +110,7 @@ bool DHTBucket::isInRange(const unsigned char* nodeID,
 bool DHTBucket::addNode(const std::shared_ptr<DHTNode>& node)
 {
   notifyUpdate();
-  std::deque<std::shared_ptr<DHTNode> >::iterator itr =
+  auto itr =
     std::find_if(nodes_.begin(), nodes_.end(), derefEqual(node));
   if(itr == nodes_.end()) {
     if(nodes_.size() < K) {
@@ -144,7 +144,7 @@ void DHTBucket::cacheNode(const std::shared_ptr<DHTNode>& node)
 void DHTBucket::dropNode(const std::shared_ptr<DHTNode>& node)
 {
   if(!cachedNodes_.empty()) {
-    std::deque<std::shared_ptr<DHTNode> >::iterator itr =
+    auto itr =
       std::find_if(nodes_.begin(), nodes_.end(), derefEqual(node));
     if(itr != nodes_.end()) {
       nodes_.erase(itr);
@@ -156,7 +156,7 @@ void DHTBucket::dropNode(const std::shared_ptr<DHTNode>& node)
 
 void DHTBucket::moveToHead(const std::shared_ptr<DHTNode>& node)
 {
-  std::deque<std::shared_ptr<DHTNode> >::iterator itr =
+  auto itr =
     std::find_if(nodes_.begin(), nodes_.end(), derefEqual(node));
   if(itr != nodes_.end()) {
     nodes_.erase(itr);
@@ -166,7 +166,7 @@ void DHTBucket::moveToHead(const std::shared_ptr<DHTNode>& node)
 
 void DHTBucket::moveToTail(const std::shared_ptr<DHTNode>& node)
 {
-  std::deque<std::shared_ptr<DHTNode> >::iterator itr =
+  auto itr =
     std::find_if(nodes_.begin(), nodes_.end(), derefEqual(node));
   if(itr != nodes_.end()) {
     nodes_.erase(itr);
@@ -196,12 +196,11 @@ std::shared_ptr<DHTBucket> DHTBucket::split()
                                                 rMax, rMin, localNode_));
 
   std::deque<std::shared_ptr<DHTNode> > lNodes;
-  for(std::deque<std::shared_ptr<DHTNode> >::iterator i = nodes_.begin(),
-        eoi = nodes_.end(); i != eoi; ++i) {
-    if(rBucket->isInRange(*i)) {
-      assert(rBucket->addNode(*i));
+  for(auto & elem : nodes_) {
+    if(rBucket->isInRange(elem)) {
+      assert(rBucket->addNode(elem));
     } else {
-      lNodes.push_back(*i);
+      lNodes.push_back(elem);
     }
   }
   nodes_ = lNodes;
@@ -231,7 +230,7 @@ std::shared_ptr<DHTNode> DHTBucket::getNode(const unsigned char* nodeID, const s
   std::shared_ptr<DHTNode> node(new DHTNode(nodeID));
   node->setIPAddress(ipaddr);
   node->setPort(port);
-  std::deque<std::shared_ptr<DHTNode> >::const_iterator itr =
+  auto itr =
     std::find_if(nodes_.begin(), nodes_.end(), derefEqual(node));
   if(itr == nodes_.end() ||
      (*itr)->getIPAddress() != ipaddr || (*itr)->getPort() != port) {
@@ -275,7 +274,7 @@ bool DHTBucket::containsQuestionableNode() const
 
 std::shared_ptr<DHTNode> DHTBucket::getLRUQuestionableNode() const
 {
-  std::deque<std::shared_ptr<DHTNode> >::const_iterator i =
+  auto i =
     std::find_if(nodes_.begin(), nodes_.end(), FindQuestionableNode());
   if(i == nodes_.end()) {
     return nullptr;

+ 16 - 16
src/DHTBucketRefreshTask.cc

@@ -56,23 +56,23 @@ void DHTBucketRefreshTask::startup()
 {
   std::vector<std::shared_ptr<DHTBucket> > buckets;
   getRoutingTable()->getBuckets(buckets);
-  for(std::vector<std::shared_ptr<DHTBucket> >::iterator i = buckets.begin(),
-        eoi = buckets.end(); i != eoi; ++i) {
-    if(forceRefresh_ || (*i)->needsRefresh()) {
-      (*i)->notifyUpdate();
-      unsigned char targetID[DHT_ID_LENGTH];
-      (*i)->getRandomNodeID(targetID);
-      std::shared_ptr<DHTNodeLookupTask> task(new DHTNodeLookupTask(targetID));
-      task->setRoutingTable(getRoutingTable());
-      task->setMessageDispatcher(getMessageDispatcher());
-      task->setMessageFactory(getMessageFactory());
-      task->setTaskQueue(getTaskQueue());
-      task->setLocalNode(getLocalNode());
-
-      A2_LOG_INFO(fmt("Dispating bucket refresh. targetID=%s",
-                      util::toHex(targetID, DHT_ID_LENGTH).c_str()));
-      getTaskQueue()->addPeriodicTask1(task);
+  for (auto& b : buckets) {
+    if(!forceRefresh_ && ! b->needsRefresh()) {
+      continue;
     }
+    b->notifyUpdate();
+    unsigned char targetID[DHT_ID_LENGTH];
+    b->getRandomNodeID(targetID);
+    std::shared_ptr<DHTNodeLookupTask> task(new DHTNodeLookupTask(targetID));
+    task->setRoutingTable(getRoutingTable());
+    task->setMessageDispatcher(getMessageDispatcher());
+    task->setMessageFactory(getMessageFactory());
+    task->setTaskQueue(getTaskQueue());
+    task->setLocalNode(getLocalNode());
+
+    A2_LOG_INFO(fmt("Dispating bucket refresh. targetID=%s",
+                    util::toHex(targetID, DHT_ID_LENGTH).c_str()));
+    getTaskQueue()->addPeriodicTask1(task);
   }
   setFinished(true);
 }

+ 2 - 3
src/DHTConnectionImpl.cc

@@ -63,9 +63,8 @@ bool DHTConnectionImpl::bind
   }
   std::random_shuffle(ports.begin(), ports.end(),
                       *SimpleRandomizer::getInstance());
-  for(std::vector<uint16_t>::const_iterator i = ports.begin(),
-        eoi = ports.end(); i != eoi; ++i) {
-    port = *i;
+  for (const auto& p : ports) {
+    port = p;
     if(bind(port, addr)) {
       return true;
     }

+ 2 - 2
src/DHTMessageFactoryImpl.cc

@@ -428,8 +428,8 @@ DHTMessageFactoryImpl::createGetPeersReplyMessage
   std::vector<std::shared_ptr<Peer>> peers;
   size_t clen = bittorrent::getCompactLength(family_);
   if(valuesList) {
-    for(auto i = valuesList->begin(), eoi = valuesList->end(); i != eoi; ++i) {
-      const String* data = downcast<String>(*i);
+    for(auto & elem : *valuesList) {
+      const String* data = downcast<String>(elem);
       if(data && data->s().size() == clen) {
         auto addr = bittorrent::unpackcompact(data->uc(), family_);
         if(addr.first.empty()) {

+ 3 - 4
src/DHTPeerAnnounceEntry.cc

@@ -51,7 +51,7 @@ DHTPeerAnnounceEntry::~DHTPeerAnnounceEntry() {}
 
 void DHTPeerAnnounceEntry::addPeerAddrEntry(const PeerAddrEntry& entry)
 {
-  std::vector<PeerAddrEntry>::iterator i =
+  auto i =
     std::find(peerAddrEntries_.begin(), peerAddrEntries_.end(), entry);
   if(i == peerAddrEntries_.end()) {
     peerAddrEntries_.push_back(entry);
@@ -98,9 +98,8 @@ bool DHTPeerAnnounceEntry::empty() const
 void DHTPeerAnnounceEntry::getPeers
 (std::vector<std::shared_ptr<Peer> >& peers) const
 {
-  for(std::vector<PeerAddrEntry>::const_iterator i = peerAddrEntries_.begin(),
-        eoi = peerAddrEntries_.end(); i != eoi; ++i) {
-    std::shared_ptr<Peer> peer(new Peer((*i).getIPAddress(), (*i).getPort()));
+  for (const auto& p: peerAddrEntries_) {
+    std::shared_ptr<Peer> peer(new Peer(p.getIPAddress(), p.getPort()));
     peers.push_back(peer);
   }
 }

+ 8 - 11
src/DHTPeerAnnounceStorage.cc

@@ -139,18 +139,15 @@ void DHTPeerAnnounceStorage::handleTimeout()
 void DHTPeerAnnounceStorage::announcePeer()
 {
   A2_LOG_DEBUG("Now announcing peer.");
-  for(DHTPeerAnnounceEntrySet::iterator i =
-        entries_.begin(), eoi = entries_.end(); i != eoi; ++i) {
-    if((*i)->getLastUpdated().
-       difference(global::wallclock()) >= DHT_PEER_ANNOUNCE_INTERVAL) {
-      (*i)->notifyUpdate();
-      std::shared_ptr<DHTTask> task =
-        taskFactory_->createPeerAnnounceTask((*i)->getInfoHash());
-      taskQueue_->addPeriodicTask2(task);
-      A2_LOG_DEBUG
-        (fmt("Added 1 peer announce: infoHash=%s",
-             util::toHex((*i)->getInfoHash(), DHT_ID_LENGTH).c_str()));
+  for (auto& e: entries_) {
+    if(e->getLastUpdated().difference(global::wallclock()) < DHT_PEER_ANNOUNCE_INTERVAL) {
+      continue;
     }
+    e->notifyUpdate();
+    auto task = taskFactory_->createPeerAnnounceTask(e->getInfoHash());
+    taskQueue_->addPeriodicTask2(task);
+    A2_LOG_DEBUG(fmt("Added 1 peer announce: infoHash=%s",
+                     util::toHex(e->getInfoHash(), DHT_ID_LENGTH).c_str()));
   }
 }
 

+ 2 - 2
src/DHTTokenTracker.cc

@@ -91,8 +91,8 @@ bool DHTTokenTracker::validateToken(const std::string& token,
                                     const unsigned char* infoHash,
                                     const std::string& ipaddr, uint16_t port) const
 {
-  for(int i = 0; i < 2; ++i) {
-    if(generateToken(infoHash, ipaddr, port, secret_[i]) == token) {
+  for(auto & elem : secret_) {
+    if(generateToken(infoHash, ipaddr, port, elem) == token) {
       return true;
     }
   }

+ 7 - 10
src/DNSCache.cc

@@ -91,8 +91,7 @@ bool DNSCache::CacheEntry::add(const std::string& addr)
 std::vector<DNSCache::AddrEntry>::iterator DNSCache::CacheEntry::find
 (const std::string& addr)
 {
-  for(std::vector<AddrEntry>::iterator i = addrEntries_.begin(),
-        eoi = addrEntries_.end(); i != eoi; ++i) {
+  for(auto i = addrEntries_.begin(), eoi = addrEntries_.end(); i != eoi; ++i) {
     if((*i).addr_ == addr) {
       return i;
     }
@@ -103,8 +102,7 @@ std::vector<DNSCache::AddrEntry>::iterator DNSCache::CacheEntry::find
 std::vector<DNSCache::AddrEntry>::const_iterator DNSCache::CacheEntry::find
 (const std::string& addr) const
 {
-  for(std::vector<AddrEntry>::const_iterator i = addrEntries_.begin(),
-        eoi = addrEntries_.end(); i != eoi; ++i) {
+  for(auto i = addrEntries_.begin(), eoi = addrEntries_.end(); i != eoi; ++i) {
     if((*i).addr_ == addr) {
       return i;
     }
@@ -119,10 +117,9 @@ bool DNSCache::CacheEntry::contains(const std::string& addr) const
 
 const std::string& DNSCache::CacheEntry::getGoodAddr() const
 {
-  for(std::vector<AddrEntry>::const_iterator i = addrEntries_.begin(),
-        eoi = addrEntries_.end(); i != eoi; ++i) {
-    if((*i).good_) {
-      return (*i).addr_;
+  for(auto & elem : addrEntries_) {
+    if(elem.good_) {
+      return (elem).addr_;
     }
   }
   return A2STR::NIL;
@@ -130,9 +127,9 @@ const std::string& DNSCache::CacheEntry::getGoodAddr() const
 
 void DNSCache::CacheEntry::markBad(const std::string& addr)
 {
-  std::vector<AddrEntry>::iterator i = find(addr);
+  auto i = find(addr);
   if(i != addrEntries_.end()) {
-    (*i).good_ = false;
+    i->good_ = false;
   }
 }
 

+ 3 - 4
src/DNSCache.h

@@ -83,10 +83,9 @@ private:
     template<typename OutputIterator>
     void getAllGoodAddrs(OutputIterator out) const
     {
-      for(std::vector<AddrEntry>::const_iterator i = addrEntries_.begin(),
-            eoi = addrEntries_.end(); i != eoi; ++i) {
-        if((*i).good_) {
-          *out++ = (*i).addr_;
+      for(auto & elem : addrEntries_) {
+        if(elem.good_) {
+          *out++ = elem.addr_;
         }
       }
     }

+ 2 - 5
src/DefaultBtAnnounce.cc

@@ -363,11 +363,8 @@ void DefaultBtAnnounce::processUDPTrackerResponse
   incomplete_ = reply->leechers;
   A2_LOG_DEBUG(fmt("Incomplete:%d", reply->leechers));
   if(!btRuntime_->isHalt() && btRuntime_->lessThanMinPeers()) {
-    for(std::vector<std::pair<std::string, uint16_t> >::iterator i =
-          reply->peers.begin(), eoi = reply->peers.end(); i != eoi;
-        ++i) {
-      peerStorage_->addPeer(std::shared_ptr<Peer>(new Peer((*i).first,
-                                                        (*i).second)));
+    for(auto & elem : reply->peers) {
+      peerStorage_->addPeer(std::make_shared<Peer>(elem.first, elem.second));
     }
   }
 }

+ 3 - 4
src/DefaultBtRequestFactory.cc

@@ -150,10 +150,9 @@ void DefaultBtRequestFactory::doChokedAction()
 }
 
 void DefaultBtRequestFactory::removeAllTargetPiece() {
-  for(std::deque<std::shared_ptr<Piece> >::iterator itr = pieces_.begin(),
-        eoi = pieces_.end(); itr != eoi; ++itr) {
-    dispatcher_->doAbortOutstandingRequestAction(*itr);
-    pieceStorage_->cancelPiece(*itr, cuid_);
+  for(auto & elem : pieces_) {
+    dispatcher_->doAbortOutstandingRequestAction(elem);
+    pieceStorage_->cancelPiece(elem, cuid_);
   }
   pieces_.clear();
 }

+ 9 - 7
src/DefaultPeerStorage.cc

@@ -116,7 +116,7 @@ void DefaultPeerStorage::addPeer(const std::vector<std::shared_ptr<Peer> >& peer
 {
   size_t added = 0;
   size_t addMax = std::min(maxPeerListSize_, MAX_PEER_LIST_UPDATE);
-  for(std::vector<std::shared_ptr<Peer> >::const_iterator itr = peers.begin(),
+  for(auto itr = peers.begin(),
         eoi = peers.end(); itr != eoi && added < addMax; ++itr) {
     const std::shared_ptr<Peer>& peer = *itr;
     if(isPeerAlreadyAdded(peer)) {
@@ -148,7 +148,7 @@ void DefaultPeerStorage::addDroppedPeer(const std::shared_ptr<Peer>& peer)
 {
   // Make sure that duplicated peers exist in droppedPeers_. If
   // exists, erase older one.
-  for(std::deque<std::shared_ptr<Peer> >::iterator i = droppedPeers_.begin(),
+  for(auto i = droppedPeers_.begin(),
         eoi = droppedPeers_.end(); i != eoi; ++i) {
     if((*i)->getIPAddress() == peer->getIPAddress() &&
        (*i)->getPort() == peer->getPort()) {
@@ -183,21 +183,23 @@ bool DefaultPeerStorage::isPeerAvailable() {
 
 bool DefaultPeerStorage::isBadPeer(const std::string& ipaddr)
 {
-  std::map<std::string, time_t>::iterator i = badPeers_.find(ipaddr);
+  auto i = badPeers_.find(ipaddr);
   if(i == badPeers_.end()) {
     return false;
-  } else if(global::wallclock().getTime() >= (*i).second) {
+  }
+
+  if(global::wallclock().getTime() >= (*i).second) {
     badPeers_.erase(i);
     return false;
-  } else {
-    return true;
   }
+
+  return true;
 }
 
 void DefaultPeerStorage::addBadPeer(const std::string& ipaddr)
 {
   if(lastBadPeerCleaned_.difference(global::wallclock()) >= 3600) {
-    for(std::map<std::string, time_t>::iterator i = badPeers_.begin(),
+    for(auto i = badPeers_.begin(),
           eoi = badPeers_.end(); i != eoi;) {
       if(global::wallclock().getTime() >= (*i).second) {
         A2_LOG_DEBUG(fmt("Purge %s from bad peer", (*i).first.c_str()));

+ 20 - 27
src/DefaultPieceStorage.cc

@@ -247,11 +247,10 @@ void unsetExcludedIndexes(BitfieldMan& bitfield,
 void DefaultPieceStorage::createFastIndexBitfield
 (BitfieldMan& bitfield, const std::shared_ptr<Peer>& peer)
 {
-  for(std::set<size_t>::const_iterator itr =
-        peer->getPeerAllowedIndexSet().begin(),
-        eoi = peer->getPeerAllowedIndexSet().end(); itr != eoi; ++itr) {
-    if(!bitfieldMan_->isBitSet(*itr) && peer->hasPiece(*itr)) {
-      bitfield.setBit(*itr);
+  const auto& is = peer->getPeerAllowedIndexSet();
+  for(const auto& i: is) {
+    if(!bitfieldMan_->isBitSet(i) && peer->hasPiece(i)) {
+      bitfield.setBit(i);
     }
   }
 }
@@ -567,9 +566,8 @@ int64_t DefaultPieceStorage::getFilteredCompletedLength()
 int64_t DefaultPieceStorage::getInFlightPieceCompletedLength() const
 {
   int64_t len = 0;
-  for(UsedPieceSet::const_iterator i = usedPieces_.begin(),
-        eoi = usedPieces_.end(); i != eoi; ++i) {
-    len += (*i)->getCompletedLength();
+  for(auto & elem : usedPieces_) {
+    len += elem->getCompletedLength();
   }
   return len;
 }
@@ -577,10 +575,9 @@ int64_t DefaultPieceStorage::getInFlightPieceCompletedLength() const
 int64_t DefaultPieceStorage::getInFlightPieceFilteredCompletedLength() const
 {
   int64_t len = 0;
-  for(UsedPieceSet::const_iterator i = usedPieces_.begin(),
-        eoi = usedPieces_.end(); i != eoi; ++i) {
-    if(bitfieldMan_->isFilterBitSet((*i)->getIndex())) {
-      len += (*i)->getCompletedLength();
+  for(auto & elem : usedPieces_) {
+    if(bitfieldMan_->isFilterBitSet(elem->getIndex())) {
+      len += elem->getCompletedLength();
     }
   }
   return len;
@@ -592,10 +589,8 @@ void DefaultPieceStorage::setupFileFilter()
   const std::vector<std::shared_ptr<FileEntry> >& fileEntries =
     downloadContext_->getFileEntries();
   bool allSelected = true;
-  for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
-        fileEntries.begin(), eoi = fileEntries.end();
-      i != eoi; ++i) {
-    if(!(*i)->isRequested()) {
+  for(auto & e : fileEntries) {
+    if(!e->isRequested()) {
       allSelected = false;
       break;
     }
@@ -603,10 +598,9 @@ void DefaultPieceStorage::setupFileFilter()
   if(allSelected) {
     return;
   }
-  for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
-        fileEntries.begin(), eoi = fileEntries.end(); i != eoi; ++i) {
-    if((*i)->isRequested()) {
-      bitfieldMan_->addFilter((*i)->getOffset(), (*i)->getLength());
+  for(auto & e: fileEntries) {
+    if(e->isRequested()) {
+      bitfieldMan_->addFilter(e->getOffset(), e->getLength());
     }
   }
   bitfieldMan_->enableFilter();
@@ -697,12 +691,11 @@ void DefaultPieceStorage::flushWrDiskCacheEntry()
   // UsedPieceSet is sorted by piece index. It means we can flush
   // cache by non-decreasing offset, which is good to reduce disk seek
   // unless the file is heavily fragmented.
-  for(UsedPieceSet::const_iterator i = usedPieces_.begin(),
-        eoi = usedPieces_.end(); i != eoi; ++i) {
-    WrDiskCacheEntry* ce = (*i)->getWrDiskCacheEntry();
+  for(auto & piece : usedPieces_) {
+    auto ce = piece->getWrDiskCacheEntry();
     if(ce) {
-      (*i)->flushWrCache(wrDiskCache_);
-      (*i)->releaseWrCache(wrDiskCache_);
+      piece->flushWrCache(wrDiskCache_);
+      piece->releaseWrCache(wrDiskCache_);
     }
   }
 }
@@ -753,8 +746,8 @@ public:
 
 void DefaultPieceStorage::removeAdvertisedPiece(time_t elapsed)
 {
-  std::deque<HaveEntry>::iterator itr =
-    std::find_if(haves_.begin(), haves_.end(), FindElapsedHave(elapsed));
+  auto itr = std::find_if(haves_.begin(), haves_.end(),
+                          FindElapsedHave(elapsed));
   if(itr != haves_.end()) {
     A2_LOG_DEBUG(fmt(MSG_REMOVED_HAVE_ENTRY,
                      static_cast<unsigned long>(haves_.end()-itr)));

+ 7 - 10
src/DownloadContext.cc

@@ -101,9 +101,8 @@ DownloadContext::findFileEntryByOffset(int64_t offset) const
 
   std::shared_ptr<FileEntry> obj(new FileEntry());
   obj->setOffset(offset);
-  std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
-    std::upper_bound(fileEntries_.begin(), fileEntries_.end(), obj,
-                     DerefLess<std::shared_ptr<FileEntry> >());
+  auto i = std::upper_bound(fileEntries_.begin(), fileEntries_.end(), obj,
+                            DerefLess<std::shared_ptr<FileEntry> >());
   if(i != fileEntries_.end() && (*i)->getOffset() == offset) {
     return *i;
   } else {
@@ -216,10 +215,9 @@ const std::string& DownloadContext::getBasePath() const
 std::shared_ptr<FileEntry>
 DownloadContext::getFirstRequestedFileEntry() const
 {
-  for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
-        fileEntries_.begin(), eoi = fileEntries_.end(); i != eoi; ++i) {
-    if((*i)->isRequested()) {
-      return *i;
+  for (auto& e : fileEntries_) {
+    if(e->isRequested()) {
+      return e;
     }
   }
   return nullptr;
@@ -228,9 +226,8 @@ DownloadContext::getFirstRequestedFileEntry() const
 size_t DownloadContext::countRequestedFileEntry() const
 {
   size_t numFiles = 0;
-  for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
-        fileEntries_.begin(), eoi = fileEntries_.end(); i != eoi; ++i) {
-    if((*i)->isRequested()) {
+  for (const auto& e: fileEntries_) {
+    if(e->isRequested()) {
       ++numFiles;
     }
   }

+ 12 - 18
src/DownloadEngine.cc

@@ -304,10 +304,9 @@ void DownloadEngine::poolSocket(const std::string& key,
     std::multimap<std::string, SocketPoolEntry> newPool;
     A2_LOG_DEBUG("Scaning SocketPool and erasing timed out entry.");
     lastSocketPoolScan_ = global::wallclock();
-    for(std::multimap<std::string, SocketPoolEntry>::iterator i =
-          socketPool_.begin(), eoi = socketPool_.end(); i != eoi; ++i) {
-      if(!(*i).second.isTimeout()) {
-        newPool.insert(*i);
+    for(auto & elem : socketPool_) {
+      if(!elem.second.isTimeout()) {
+        newPool.insert(elem);
       }
     }
     A2_LOG_DEBUG(fmt("%lu entries removed.",
@@ -425,8 +424,7 @@ DownloadEngine::findSocketPoolEntry(const std::string& key)
   std::pair<std::multimap<std::string, SocketPoolEntry>::iterator,
     std::multimap<std::string, SocketPoolEntry>::iterator> range =
     socketPool_.equal_range(key);
-  for(std::multimap<std::string, SocketPoolEntry>::iterator i =
-        range.first, eoi = range.second; i != eoi; ++i) {
+  for(auto i = range.first, eoi = range.second; i != eoi; ++i) {
     const SocketPoolEntry& e = (*i).second;
     // We assume that if socket is readable it means peer shutdowns
     // connection and the socket will receive EOF. So skip it.
@@ -444,9 +442,8 @@ DownloadEngine::popPooledSocket
  const std::string& proxyhost, uint16_t proxyport)
 {
   std::shared_ptr<SocketCore> s;
-  std::multimap<std::string, SocketPoolEntry>::iterator i =
-    findSocketPoolEntry
-    (createSockPoolKey(ipaddr, port, A2STR::NIL, proxyhost, proxyport));
+  auto i = findSocketPoolEntry(createSockPoolKey(ipaddr, port, A2STR::NIL,
+                                                 proxyhost, proxyport));
   if(i != socketPool_.end()) {
     s = (*i).second.getSocket();
     socketPool_.erase(i);
@@ -462,9 +459,8 @@ DownloadEngine::popPooledSocket
  const std::string& proxyhost, uint16_t proxyport)
 {
   std::shared_ptr<SocketCore> s;
-  std::multimap<std::string, SocketPoolEntry>::iterator i =
-    findSocketPoolEntry
-    (createSockPoolKey(ipaddr, port, username, proxyhost, proxyport));
+  auto i = findSocketPoolEntry(createSockPoolKey(ipaddr, port, username,
+                                                 proxyhost, proxyport));
   if(i != socketPool_.end()) {
     s = (*i).second.getSocket();
     options = (*i).second.getOptions();
@@ -478,9 +474,8 @@ DownloadEngine::popPooledSocket
 (const std::vector<std::string>& ipaddrs, uint16_t port)
 {
   std::shared_ptr<SocketCore> s;
-  for(std::vector<std::string>::const_iterator i = ipaddrs.begin(),
-        eoi = ipaddrs.end(); i != eoi; ++i) {
-    s = popPooledSocket(*i, port, A2STR::NIL, 0);
+  for(const auto & ipaddr : ipaddrs) {
+    s = popPooledSocket(ipaddr, port, A2STR::NIL, 0);
     if(s) {
       break;
     }
@@ -495,9 +490,8 @@ DownloadEngine::popPooledSocket
  const std::string& username)
 {
   std::shared_ptr<SocketCore> s;
-  for(std::vector<std::string>::const_iterator i = ipaddrs.begin(),
-        eoi = ipaddrs.end(); i != eoi; ++i) {
-    s = popPooledSocket(options, *i, port, username, A2STR::NIL, 0);
+  for(const auto & ipaddr : ipaddrs) {
+    s = popPooledSocket(options, ipaddr, port, username, A2STR::NIL, 0);
     if(s) {
       break;
     }

+ 26 - 28
src/FeedbackURISelector.cc

@@ -61,11 +61,10 @@ std::string FeedbackURISelector::select
  const std::vector<std::pair<size_t, std::string> >& usedHosts)
 {
   if(A2_LOG_DEBUG_ENABLED) {
-    for(std::vector<std::pair<size_t, std::string> >::const_iterator i =
-          usedHosts.begin(), eoi = usedHosts.end(); i != eoi; ++i) {
+    for (const auto& h: usedHosts) {
       A2_LOG_DEBUG(fmt("UsedHost=%lu, %s",
-                       static_cast<unsigned long>((*i).first),
-                       (*i).second.c_str()));
+                       static_cast<unsigned long>(h.first),
+                       h.second.c_str()));
     }
   }
   if(fileEntry->getRemainingUris().empty()) {
@@ -92,27 +91,24 @@ std::string FeedbackURISelector::selectRarer
 {
   // pair of host and URI
   std::vector<std::pair<std::string, std::string> > cands;
-  for(std::deque<std::string>::const_iterator i = uris.begin(),
-        eoi = uris.end(); i != eoi; ++i) {
+  for (const auto& u: uris) {
     uri_split_result us;
-    if(uri_split(&us, (*i).c_str()) == -1) {
+    if(uri_split(&us, u.c_str()) == -1) {
       continue;
     }
-    std::string host = uri::getFieldString(us, USR_HOST, (*i).c_str());
-    std::string protocol = uri::getFieldString(us, USR_SCHEME, (*i).c_str());
-    std::shared_ptr<ServerStat> ss = serverStatMan_->find(host, protocol);
+    auto host = uri::getFieldString(us, USR_HOST, u.c_str());
+    auto protocol = uri::getFieldString(us, USR_SCHEME, u.c_str());
+    auto ss = serverStatMan_->find(host, protocol);
     if(ss && ss->isError()) {
-      A2_LOG_DEBUG(fmt("Error not considered: %s", (*i).c_str()));
+      A2_LOG_DEBUG(fmt("Error not considered: %s", u.c_str()));
       continue;
     }
-    cands.push_back(std::make_pair(host, *i));
+    cands.push_back(std::make_pair(host, u));
   }
-  for(std::vector<std::pair<size_t, std::string> >::const_iterator i =
-        usedHosts.begin(), eoi = usedHosts.end(); i != eoi; ++i) {
-    for(std::vector<std::pair<std::string, std::string> >::const_iterator j =
-          cands.begin(), eoj = cands.end(); j != eoj; ++j) {
-      if((*i).second == (*j).first) {
-        return (*j).second;
+  for (const auto& h: usedHosts) {
+    for (const auto& c: cands) {
+      if(h.second == c.first) {
+        return c.second;
       }
     }
   }
@@ -130,27 +126,29 @@ std::string FeedbackURISelector::selectFaster
   const int SPEED_THRESHOLD = 20*1024;
   std::vector<std::pair<std::shared_ptr<ServerStat>, std::string> > fastCands;
   std::vector<std::string> normCands;
-  for(std::deque<std::string>::const_iterator i = uris.begin(),
-        eoi = uris.end(); i != eoi && fastCands.size() < NUM_URI; ++i) {
+  for (const auto& u: uris) {
+    if (fastCands.size() >=  NUM_URI) {
+      break;
+    }
     uri_split_result us;
-    if(uri_split(&us, (*i).c_str()) == -1) {
+    if(uri_split(&us, u.c_str()) == -1) {
       continue;
     }
-    std::string host = uri::getFieldString(us, USR_HOST, (*i).c_str());
+    auto host = uri::getFieldString(us, USR_HOST, u.c_str());
     if(findSecond(usedHosts.begin(), usedHosts.end(), host) !=
        usedHosts.end()) {
-      A2_LOG_DEBUG(fmt("%s is in usedHosts, not considered", (*i).c_str()));
+      A2_LOG_DEBUG(fmt("%s is in usedHosts, not considered", u.c_str()));
       continue;
     }
-    std::string protocol = uri::getFieldString(us, USR_SCHEME, (*i).c_str());
-    std::shared_ptr<ServerStat> ss = serverStatMan_->find(host, protocol);
+    auto protocol = uri::getFieldString(us, USR_SCHEME, u.c_str());
+    auto ss = serverStatMan_->find(host, protocol);
     if(!ss) {
-      normCands.push_back(*i);
+      normCands.push_back(u);
     } else if(ss->isOK()) {
       if(ss->getDownloadSpeed() > SPEED_THRESHOLD) {
-        fastCands.push_back(std::make_pair(ss, *i));
+        fastCands.push_back(std::make_pair(ss, u));
       } else {
-        normCands.push_back(*i);
+        normCands.push_back(u);
       }
     }
   }

+ 34 - 40
src/FileEntry.cc

@@ -382,9 +382,8 @@ public:
 void FileEntry::extractURIResult
 (std::deque<URIResult>& res, error_code::Value r)
 {
-  std::deque<URIResult>::iterator i =
-    std::stable_partition(uriResults_.begin(), uriResults_.end(),
-                          FindURIResultByResult(r));
+  auto i = std::stable_partition(uriResults_.begin(), uriResults_.end(),
+                                 FindURIResultByResult(r));
   std::copy(uriResults_.begin(), i, std::back_inserter(res));
   uriResults_.erase(uriResults_.begin(), i);
 }
@@ -392,9 +391,8 @@ void FileEntry::extractURIResult
 void FileEntry::reuseUri(const std::vector<std::string>& ignore)
 {
   if(A2_LOG_DEBUG_ENABLED) {
-    for(std::vector<std::string>::const_iterator i = ignore.begin(),
-          eoi = ignore.end(); i != eoi; ++i) {
-      A2_LOG_DEBUG(fmt("ignore host=%s", (*i).c_str()));
+    for (const auto& i: ignore) {
+      A2_LOG_DEBUG(fmt("ignore host=%s", i.c_str()));
     }
   }
   std::deque<std::string> uris = spentUris_;
@@ -417,8 +415,8 @@ void FileEntry::reuseUri(const std::vector<std::string>& ignore)
   std::set_difference(uris.begin(), uris.end(),
                       errorUris.begin(), errorUris.end(),
                       std::back_inserter(reusableURIs));
-  std::vector<std::string>::iterator insertionPoint = reusableURIs.begin();
-  for(std::vector<std::string>::iterator i = reusableURIs.begin(),
+  auto insertionPoint = reusableURIs.begin();
+  for(auto i = reusableURIs.begin(),
         eoi = reusableURIs.end(); i != eoi; ++i) {
     uri_split_result us;
     if(uri_split(&us, (*i).c_str()) == 0 &&
@@ -485,36 +483,32 @@ InputIterator findRequestByUri
 
 bool FileEntry::removeUri(const std::string& uri)
 {
-  std::deque<std::string>::iterator itr =
-    std::find(spentUris_.begin(), spentUris_.end(), uri);
+  auto itr = std::find(spentUris_.begin(), spentUris_.end(), uri);
   if(itr == spentUris_.end()) {
     itr = std::find(uris_.begin(), uris_.end(), uri);
     if(itr == uris_.end()) {
       return false;
-    } else {
-      uris_.erase(itr);
+    }
+    uris_.erase(itr);
+    return true;
+  }
+  spentUris_.erase(itr);
+  std::shared_ptr<Request> req;
+  InFlightRequestSet::iterator riter =
+    findRequestByUri(inFlightRequests_.begin(), inFlightRequests_.end(), uri);
+  if(riter == inFlightRequests_.end()) {
+    RequestPool::iterator riter = findRequestByUri(requestPool_.begin(),
+                                                    requestPool_.end(), uri);
+    if(riter == requestPool_.end()) {
       return true;
     }
+    req = *riter;
+    requestPool_.erase(riter);
   } else {
-    spentUris_.erase(itr);
-    std::shared_ptr<Request> req;
-    InFlightRequestSet::iterator riter =
-      findRequestByUri(inFlightRequests_.begin(), inFlightRequests_.end(), uri);
-    if(riter == inFlightRequests_.end()) {
-      RequestPool::iterator riter = findRequestByUri(requestPool_.begin(),
-                                                     requestPool_.end(), uri);
-      if(riter == requestPool_.end()) {
-        return true;
-      } else {
-        req = *riter;
-        requestPool_.erase(riter);
-      }
-    } else {
-      req = *riter;
-    }
-    req->requestRemoval();
-    return true;
+    req = *riter;
   }
+  req->requestRemoval();
+  return true;
 }
 
 std::string FileEntry::getBasename() const
@@ -547,13 +541,12 @@ bool FileEntry::addUri(const std::string& uri)
 bool FileEntry::insertUri(const std::string& uri, size_t pos)
 {
   std::string peUri = util::percentEncodeMini(uri);
-  if(uri_split(nullptr, peUri.c_str()) == 0) {
-    pos = std::min(pos, uris_.size());
-    uris_.insert(uris_.begin()+pos, peUri);
-    return true;
-  } else {
+  if(uri_split(nullptr, peUri.c_str()) != 0) {
     return false;
   }
+  pos = std::min(pos, uris_.size());
+  uris_.insert(uris_.begin()+pos, peUri);
+  return true;
 }
 
 void FileEntry::setPath(const std::string& path)
@@ -599,12 +592,13 @@ void writeFilePath
     } else {
       o << uris.front();
     }
+    return;
+  }
+
+  if(memory) {
+    o << "[MEMORY]" << File(entry->getPath()).getBasename();
   } else {
-    if(memory) {
-      o << "[MEMORY]" << File(entry->getPath()).getBasename();
-    } else {
-      o << entry->getPath();
-    }
+    o << entry->getPath();
   }
 }
 

+ 1 - 1
src/GroupId.cc

@@ -87,7 +87,7 @@ int GroupId::expandUnique(a2_gid_t& n, const char* hex)
   }
   p <<= 64-i*4;
   a2_gid_t mask = UINT64_MAX-((1LL << (64-i*4))-1);
-  std::set<a2_gid_t>::const_iterator itr = set_.lower_bound(p);
+  auto itr = set_.lower_bound(p);
   if(itr == set_.end()) {
     return ERR_NOT_FOUND;
   }

+ 4 - 5
src/HandshakeExtensionMessage.cc

@@ -185,14 +185,13 @@ HandshakeExtensionMessage::create(const unsigned char* data, size_t length)
   }
   const Dict* extDict = downcast<Dict>(dict->get("m"));
   if(extDict) {
-    for(Dict::ValueType::const_iterator i = extDict->begin(),
-          eoi = extDict->end(); i != eoi; ++i) {
-      const Integer* extId = downcast<Integer>((*i).second);
+    for(auto & elem : *extDict) {
+      const Integer* extId = downcast<Integer>(elem.second);
       if(extId) {
-        int key = keyBtExtension((*i).first.c_str());
+        int key = keyBtExtension(elem.first.c_str());
         if(key == ExtensionMessageRegistry::MAX_EXTENSION) {
           A2_LOG_DEBUG(fmt("Unsupported BitTorrent extension %s=%" PRId64,
-                           (*i).first.c_str(), extId->i()));
+                           elem.first.c_str(), extId->i()));
         } else {
           msg->setExtension(key, extId->i());
         }

+ 2 - 3
src/HaveEraseCommand.cc

@@ -57,9 +57,8 @@ void HaveEraseCommand::process()
 {
   const RequestGroupList& groups =
     getDownloadEngine()->getRequestGroupMan()->getRequestGroups();
-  for(RequestGroupList::const_iterator i = groups.begin(),
-        eoi = groups.end(); i != eoi; ++i) {
-    const std::shared_ptr<PieceStorage>& ps = (*i)->getPieceStorage();
+  for(auto & group : groups) {
+    const auto& ps = group->getPieceStorage();
     if(ps) {
       ps->removeAdvertisedPiece(5);
     }

+ 9 - 15
src/HttpHeader.cc

@@ -60,7 +60,7 @@ bool HttpHeader::defined(int hdKey) const
 
 const std::string& HttpHeader::find(int hdKey) const
 {
-  std::multimap<int, std::string>::const_iterator itr = table_.find(hdKey);
+  auto itr = table_.find(hdKey);
   if(itr == table_.end()) {
     return A2STR::NIL;
   } else {
@@ -71,9 +71,7 @@ const std::string& HttpHeader::find(int hdKey) const
 std::vector<std::string> HttpHeader::findAll(int hdKey) const
 {
   std::vector<std::string> v;
-  std::pair<std::multimap<int, std::string>::const_iterator,
-            std::multimap<int, std::string>::const_iterator> itrpair =
-    table_.equal_range(hdKey);
+  auto itrpair = table_.equal_range(hdKey);
   while(itrpair.first != itrpair.second) {
     v.push_back((*itrpair.first).second);
     ++itrpair.first;
@@ -90,7 +88,7 @@ HttpHeader::equalRange(int hdKey) const
 
 Range HttpHeader::getRange() const
 {
-  const std::string& rangeStr = find(CONTENT_RANGE);
+  const auto& rangeStr = find(CONTENT_RANGE);
   if(rangeStr.empty()) {
     const std::string& clenStr = find(CONTENT_LENGTH);
     if(clenStr.empty()) {
@@ -113,8 +111,7 @@ Range HttpHeader::getRange() const
   // we expect that rangeStr looks like 'bytes 100-199/100'
   // but some server returns '100-199/100', omitting bytes-unit sepcifier
   // 'bytes'.
-  std::string::const_iterator byteRangeSpec =
-    std::find(rangeStr.begin(), rangeStr.end(), ' ');
+  auto byteRangeSpec = std::find(rangeStr.begin(), rangeStr.end(), ' ');
   if(byteRangeSpec == rangeStr.end()) {
     // we assume bytes-unit specifier omitted.
     byteRangeSpec = rangeStr.begin();
@@ -124,8 +121,7 @@ Range HttpHeader::getRange() const
       ++byteRangeSpec;
     }
   }
-  std::string::const_iterator slash =
-    std::find(byteRangeSpec, rangeStr.end(), '/');
+  auto slash = std::find(byteRangeSpec, rangeStr.end(), '/');
   if(slash == rangeStr.end() || slash+1 == rangeStr.end() ||
      (byteRangeSpec+1 == slash && *byteRangeSpec == '*') ||
      (slash+2 == rangeStr.end() && *(slash+1) == '*')) {
@@ -134,7 +130,7 @@ Range HttpHeader::getRange() const
     // not satisfiable) status.
     return Range();
   }
-  std::string::const_iterator minus = std::find(byteRangeSpec, slash, '-');
+  auto minus = std::find(byteRangeSpec, slash, '-');
   if(minus == slash) {
     return Range();
   }
@@ -218,17 +214,15 @@ bool HttpHeader::fieldContains(int hdKey, const char* value)
   std::pair<std::multimap<int, std::string>::const_iterator,
             std::multimap<int, std::string>::const_iterator> range =
     equalRange(hdKey);
-  for(std::multimap<int, std::string>::const_iterator i = range.first;
-      i != range.second; ++i) {
+  for(auto i = range.first; i != range.second; ++i) {
     std::vector<Scip> values;
     util::splitIter((*i).second.begin(), (*i).second.end(),
                     std::back_inserter(values),
                     ',',
                     true // doStrip
                     );
-    for(std::vector<Scip>::const_iterator j = values.begin(),
-          eoj = values.end(); j != eoj; ++j) {
-      if(util::strieq((*j).first, (*j).second, value)) {
+    for (const auto& v: values) {
+      if(util::strieq(v.first, v.second, value)) {
         return true;
       }
     }

+ 12 - 15
src/HttpRequest.cc

@@ -94,17 +94,16 @@ int64_t HttpRequest::getEndByte() const
 {
   if(!segment_ || !request_) {
     return 0;
-  } else {
-    if(request_->isPipeliningEnabled()) {
-      int64_t endByte =
-        fileEntry_->gtoloff(segment_->getPosition()+segment_->getLength()-1);
-      return std::min(endByte, fileEntry_->getLength()-1);
-    } else if(endOffsetOverride_ > 0) {
-      return endOffsetOverride_ - 1;
-    } else {
-      return 0;
-    }
   }
+  if(request_->isPipeliningEnabled()) {
+    int64_t endByte =
+      fileEntry_->gtoloff(segment_->getPosition()+segment_->getLength()-1);
+    return std::min(endByte, fileEntry_->getLength()-1);
+  }
+  if(endOffsetOverride_ > 0) {
+    return endOffsetOverride_ - 1;
+  }
+  return 0;
 }
 
 Range HttpRequest::getRange() const
@@ -112,9 +111,8 @@ Range HttpRequest::getRange() const
   // content-length is always 0
   if(!segment_) {
     return Range();
-  } else {
-    return Range(getStartByte(), getEndByte(), fileEntry_->getLength());
   }
+  return Range(getStartByte(), getEndByte(), fileEntry_->getLength());
 }
 
 bool HttpRequest::isRangeSatisfied(const Range& range) const
@@ -128,9 +126,8 @@ bool HttpRequest::isRangeSatisfied(const Range& range) const
      ((fileEntry_->getLength() == 0) ||
       (fileEntry_->getLength() == range.entityLength))) {
     return true;
-  } else {
-    return false;
   }
+  return false;
 }
 
 namespace {
@@ -444,7 +441,7 @@ bool HttpRequest::conditionalRequest() const
   if(!ifModSinceHeader_.empty()) {
     return true;
   }
-  for(std::vector<std::string>::const_iterator i = headers_.begin(),
+  for(auto i = headers_.begin(),
         eoi = headers_.end(); i != eoi; ++i) {
     if(util::istartsWith(*i, "if-modified-since") ||
        util::istartsWith(*i, "if-none-match")) {

+ 13 - 19
src/HttpResponse.cc

@@ -124,15 +124,13 @@ std::string HttpResponse::determinFilename() const
                           httpRequest_->getFile().end());
     if(file.empty()) {
       return "index.html";
-    } else {
-      return file;
     }
-  } else {
-    A2_LOG_INFO(fmt(MSG_CONTENT_DISPOSITION_DETECTED,
-                    cuid_,
-                    contentDisposition.c_str()));
-    return contentDisposition;
+    return file;
   }
+  A2_LOG_INFO(fmt(MSG_CONTENT_DISPOSITION_DETECTED,
+                  cuid_,
+                  contentDisposition.c_str()));
+  return contentDisposition;
 }
 
 void HttpResponse::retrieveCookie()
@@ -299,9 +297,8 @@ bool parseMetalinkHttpLink(MetalinkHttpEntry& result, const std::string& s)
             std::string::const_iterator> p = util::stripIter(first+1, last);
   if(p.first == p.second) {
     return false;
-  } else {
-    result.uri.assign(p.first, p.second);
   }
+  result.uri.assign(p.first, p.second);
   last = std::find(last, s.end(), ';');
   if(last != s.end()) {
     ++last;
@@ -363,15 +360,13 @@ void HttpResponse::getMetalinKHttpEntries
     if(option->defined(PREF_METALINK_LOCATION)) {
       const std::string& loc = option->get(PREF_METALINK_LOCATION);
       util::split(loc.begin(), loc.end(), std::back_inserter(locs), ',', true);
-      for(std::vector<std::string>::iterator i = locs.begin(), eoi = locs.end();
-          i != eoi; ++i) {
-        util::lowercase(*i);
+      for (auto& l: locs) {
+        util::lowercase(l);
       }
     }
-    for(std::vector<MetalinkHttpEntry>::iterator i = result.begin(),
-          eoi = result.end(); i != eoi; ++i) {
-      if(std::find(locs.begin(), locs.end(), (*i).geo) != locs.end()) {
-        (*i).pri -= 999999;
+    for (auto& r: result) {
+      if(std::find(locs.begin(), locs.end(), r.geo) != locs.end()) {
+        r.pri -= 999999;
       }
     }
   }
@@ -409,10 +404,9 @@ void HttpResponse::getDigest(std::vector<Checksum>& result) const
   }
   std::sort(result.begin(), result.end(), HashTypeStronger());
   std::vector<Checksum> temp;
-  for(std::vector<Checksum>::iterator i = result.begin(),
-        eoi = result.end(); i != eoi;) {
+  for(auto i = result.begin(), eoi = result.end(); i != eoi;) {
     bool ok = true;
-    std::vector<Checksum>::iterator j = i+1;
+    auto j = i+1;
     for(; j != eoi; ++j) {
       if((*i).getHashType() != (*j).getHashType()) {
         break;

+ 11 - 13
src/HttpResponseCommand.cc

@@ -194,10 +194,9 @@ bool HttpResponseCommand::executeInternal()
         getDownloadContext()->setAcceptMetalink(false);
         std::vector<MetalinkHttpEntry> entries;
         httpResponse->getMetalinKHttpEntries(entries, getOption());
-        for(std::vector<MetalinkHttpEntry>::iterator i = entries.begin(),
-              eoi = entries.end(); i != eoi; ++i) {
-          getFileEntry()->addUri((*i).uri);
-          A2_LOG_DEBUG(fmt("Adding URI=%s", (*i).uri.c_str()));
+        for(const auto& e : entries) {
+          getFileEntry()->addUri(e.uri);
+          A2_LOG_DEBUG(fmt("Adding URI=%s", e.uri.c_str()));
         }
       }
     }
@@ -205,16 +204,16 @@ bool HttpResponseCommand::executeInternal()
     if(httpHeader->defined(HttpHeader::DIGEST)) {
       std::vector<Checksum> checksums;
       httpResponse->getDigest(checksums);
-      for(std::vector<Checksum>::iterator i = checksums.begin(),
-            eoi = checksums.end(); i != eoi; ++i) {
+      for(const auto &checksum : checksums) {
         if(getDownloadContext()->getHashType().empty()) {
           A2_LOG_DEBUG(fmt("Setting digest: type=%s, digest=%s",
-                           (*i).getHashType().c_str(),
-                           (*i).getDigest().c_str()));
-          getDownloadContext()->setDigest((*i).getHashType(), (*i).getDigest());
+                           checksum.getHashType().c_str(),
+                           checksum.getDigest().c_str()));
+          getDownloadContext()->setDigest(checksum.getHashType(),
+                                          checksum.getDigest());
           break;
         } else {
-          if(checkChecksum(getDownloadContext(), *i)) {
+          if(checkChecksum(getDownloadContext(), checksum)) {
             break;
           }
         }
@@ -281,9 +280,8 @@ bool HttpResponseCommand::executeInternal()
        httpHeader->defined(HttpHeader::DIGEST)) {
       std::vector<Checksum> checksums;
       httpResponse->getDigest(checksums);
-      for(std::vector<Checksum>::iterator i = checksums.begin(),
-            eoi = checksums.end(); i != eoi; ++i) {
-        if(checkChecksum(getDownloadContext(), *i)) {
+      for(const auto &checksum : checksums) {
+        if(checkChecksum(getDownloadContext(), checksum)) {
           break;
         }
       }

+ 1 - 1
src/IndexBtMessage.cc

@@ -47,7 +47,7 @@ unsigned char* IndexBtMessage::createMessage()
    * piece index --- index, 4bytes
    * total: 9bytes
    */
-  unsigned char* msg = new unsigned char[MESSAGE_LENGTH];
+  auto   msg = new unsigned char[MESSAGE_LENGTH];
   bittorrent::createPeerMessageString(msg, MESSAGE_LENGTH, 5, getId());
   bittorrent::setIntParam(&msg[5], index_);
   return msg;

+ 12 - 16
src/LibuvEventPoll.cc

@@ -128,7 +128,7 @@ void LibuvEventPoll::poll(const struct timeval& tv)
 
   // timeout == 0 will tick once
   if (timeout >= 0) {
-    uv_timer_t* timer = new uv_timer_t;
+    auto timer = new uv_timer_t;
     uv_timer_init(loop_, timer);
     uv_timer_start(timer, timer_callback, timeout, timeout);
 
@@ -147,11 +147,10 @@ void LibuvEventPoll::poll(const struct timeval& tv)
   // own timeout and ares may create new sockets or closes socket in
   // their API. So we call ares_process_fd for all ares_channel and
   // re-register their sockets.
-  for(KAsyncNameResolverEntrySet::iterator i = nameResolverEntries_.begin(),
-        eoi = nameResolverEntries_.end(); i != eoi; ++i) {
-    (*i)->processTimeout();
-    (*i)->removeSocketEvents(this);
-    (*i)->addSocketEvents(this);
+  for (auto& r: nameResolverEntries_) {
+    r->processTimeout();
+    r->removeSocketEvents(this);
+    r->addSocketEvents(this);
   }
 #endif // ENABLE_ASYNC_DNS
 
@@ -219,8 +218,8 @@ void LibuvEventPoll::pollCallback(KPoll* poll, int status, int events)
 bool LibuvEventPoll::addEvents(sock_t socket,
                                const LibuvEventPoll::KEvent& event)
 {
-  std::shared_ptr<KSocketEntry> socketEntry(new KSocketEntry(socket));
-  KSocketEntrySet::iterator i = socketEntries_.lower_bound(socketEntry);
+  auto socketEntry = std::make_shared<KSocketEntry>(socket);
+  auto i = socketEntries_.lower_bound(socketEntry);
 
   if (i != socketEntries_.end() && **i == *socketEntry) {
     event.addSelf(*i);
@@ -234,7 +233,7 @@ bool LibuvEventPoll::addEvents(sock_t socket,
 
   socketEntries_.insert(i, socketEntry);
   event.addSelf(socketEntry);
-  KPoll* poll = new KPoll(this, socketEntry.get(), socket);
+  auto poll = new KPoll(this, socketEntry.get(), socket);
   polls_[socket] = poll;
   poll->start();
   return true;
@@ -302,10 +301,8 @@ bool LibuvEventPoll::deleteEvents(sock_t socket, Command* command,
 bool LibuvEventPoll::addNameResolver(const std::shared_ptr<AsyncNameResolver>& resolver,
                                      Command* command)
 {
-  std::shared_ptr<KAsyncNameResolverEntry> entry(
-      new KAsyncNameResolverEntry(resolver, command));
-  KAsyncNameResolverEntrySet::iterator itr =
-    nameResolverEntries_.lower_bound(entry);
+  auto entry = std::make_shared<KAsyncNameResolverEntry>(resolver, command);
+  auto itr = nameResolverEntries_.lower_bound(entry);
   if (itr != nameResolverEntries_.end() && *(*itr) == *entry) {
     return false;
   }
@@ -317,9 +314,8 @@ bool LibuvEventPoll::addNameResolver(const std::shared_ptr<AsyncNameResolver>& r
 bool LibuvEventPoll::deleteNameResolver(const std::shared_ptr<AsyncNameResolver>& resolver,
                                         Command* command)
 {
-  std::shared_ptr<KAsyncNameResolverEntry> entry(
-      new KAsyncNameResolverEntry(resolver, command));
-  KAsyncNameResolverEntrySet::iterator itr = nameResolverEntries_.find(entry);
+  auto entry = std::make_shared<KAsyncNameResolverEntry>(resolver, command);
+  auto itr = nameResolverEntries_.find(entry);
   if (itr == nameResolverEntries_.end()) {
     return false;
   }

+ 6 - 9
src/MSEHandshake.cc

@@ -107,11 +107,10 @@ MSEHandshake::HANDSHAKE_TYPE MSEHandshake::identifyHandshakeType()
     A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - This is legacy BitTorrent handshake.",
                      cuid_));
     return HANDSHAKE_LEGACY;
-  } else {
-    A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - This may be encrypted BitTorrent handshake.",
-                     cuid_));
-    return HANDSHAKE_ENCRYPTED;
   }
+  A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - This may be encrypted BitTorrent handshake.",
+                    cuid_));
+  return HANDSHAKE_ENCRYPTED;
 }
 
 void MSEHandshake::initEncryptionFacility(bool initiator)
@@ -430,17 +429,15 @@ bool MSEHandshake::receiveReceiverHashAndPadCLength
   // pointing to the position of HASH('req2', SKEY) xor HASH('req3', S)
   unsigned char* rbufptr = rbuf_;
   std::shared_ptr<DownloadContext> downloadContext;
-  for(std::vector<std::shared_ptr<DownloadContext> >::const_iterator i =
-        downloadContexts.begin(), eoi = downloadContexts.end();
-      i != eoi; ++i) {
+  for(auto & ctx : downloadContexts) {
     unsigned char md[20];
-    const unsigned char* infohash = bittorrent::getInfoHash(*i);
+    const auto infohash = bittorrent::getInfoHash(ctx);
     createReq23Hash(md, infohash);
     if(memcmp(md, rbufptr, sizeof(md)) == 0) {
       A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - info hash found: %s",
                        cuid_,
                        util::toHex(infohash, INFO_HASH_LENGTH).c_str()));
-      downloadContext = *i;
+      downloadContext = ctx;
       break;
     }
   }

+ 26 - 42
src/MetalinkParserStateV3Impl.cc

@@ -76,8 +76,7 @@ void FilesMetalinkParserState::beginElement
 {
   if(checkNsUri(nsUri) && strcmp(localname, "file") == 0) {
     psm->setFileState();
-    std::vector<XmlAttr>::const_iterator itr =
-      findAttr(attrs, "name", METALINK3_NAMESPACE_URI);
+    auto itr = findAttr(attrs, "name", METALINK3_NAMESPACE_URI);
     if(itr != attrs.end()) {
       std::string name((*itr).value, (*itr).valueLength);
       if(name.empty() || util::detectDirTraversal(name)) {
@@ -113,7 +112,7 @@ void FileMetalinkParserState::beginElement
   } else if(strcmp(localname, "resources") == 0) {
     psm->setResourcesState();
     int maxConnections;
-    std::vector<XmlAttr>::const_iterator itr =
+    auto itr =
       findAttr(attrs, "maxconnections", METALINK3_NAMESPACE_URI);
     if(itr == attrs.end()) {
       maxConnections = -1;
@@ -198,8 +197,7 @@ void VerificationMetalinkParserState::beginElement
 #ifdef ENABLE_MESSAGE_DIGEST
     if(strcmp(localname, "hash") == 0) {
       psm->setHashState();
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "type", METALINK3_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "type", METALINK3_NAMESPACE_URI);
       if(itr == attrs.end()) {
         return;
       } else {
@@ -210,8 +208,7 @@ void VerificationMetalinkParserState::beginElement
       psm->setPiecesState();
       uint32_t length;
       {
-        std::vector<XmlAttr>::const_iterator itr =
-          findAttr(attrs, "length", METALINK3_NAMESPACE_URI);
+        auto itr = findAttr(attrs, "length", METALINK3_NAMESPACE_URI);
         if(itr == attrs.end()) {
           return;
         } else {
@@ -223,8 +220,7 @@ void VerificationMetalinkParserState::beginElement
       }
       std::string type;
       {
-        std::vector<XmlAttr>::const_iterator itr =
-          findAttr(attrs, "type", METALINK3_NAMESPACE_URI);
+        auto itr = findAttr(attrs, "type", METALINK3_NAMESPACE_URI);
         if(itr == attrs.end()) {
           return;
         } else {
@@ -238,16 +234,14 @@ void VerificationMetalinkParserState::beginElement
 #endif // ENABLE_MESSAGE_DIGEST
       if(strcmp(localname, "signature") == 0) {
         psm->setSignatureState();
-        std::vector<XmlAttr>::const_iterator itr =
-          findAttr(attrs, "type", METALINK3_NAMESPACE_URI);
+        auto itr = findAttr(attrs, "type", METALINK3_NAMESPACE_URI);
         if(itr == attrs.end()) {
           return;
         } else {
           psm->newSignatureTransaction();
           psm->setTypeOfSignature
             (std::string((*itr).value, (*itr).valueLength));
-          std::vector<XmlAttr>::const_iterator itr =
-            findAttr(attrs, "file", METALINK3_NAMESPACE_URI);
+          auto itr = findAttr(attrs, "file", METALINK3_NAMESPACE_URI);
           if(itr != attrs.end()) {
             std::string file((*itr).value, (*itr).valueLength);
             if(!util::detectDirTraversal(file)) {
@@ -280,8 +274,7 @@ void PiecesMetalinkParserState::beginElement
 {
   if(checkNsUri(nsUri) && strcmp(localname, "hash") == 0) {
     psm->setPieceHashState();
-    std::vector<XmlAttr>::const_iterator itr =
-      findAttr(attrs, "piece", METALINK3_NAMESPACE_URI);
+    auto itr = findAttr(attrs, "piece", METALINK3_NAMESPACE_URI);
     if(itr == attrs.end()) {
       psm->cancelChunkChecksumTransaction();
     } else {
@@ -343,53 +336,44 @@ void ResourcesMetalinkParserState::beginElement
     psm->setURLState();
     std::string type;
     {
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "type", METALINK3_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "type", METALINK3_NAMESPACE_URI);
       if(itr == attrs.end()) {
         return;
-      } else {
-        type.assign((*itr).value, (*itr).valueLength);
       }
+      type.assign((*itr).value, (*itr).valueLength);
     }
     std::string location;
     {
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "location", METALINK3_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "location", METALINK3_NAMESPACE_URI);
       if(itr != attrs.end()) {
         location.assign((*itr).value, (*itr).valueLength);
       }
     }
     int preference;
     {
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "preference", METALINK3_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "preference", METALINK3_NAMESPACE_URI);
       if(itr == attrs.end()) {
         preference = MetalinkResource::getLowestPriority();
-      } else {
-        if(util::parseIntNoThrow
-           (preference, std::string((*itr).value, (*itr).valueLength)) &&
-           preference >= 0) {
-          // In Metalink3Spec, highest prefernce value is 100.  We
-          // use Metalink4Spec priority unit system in which 1 is
-          // higest.
-          preference = 101-preference;
-        } else {
-          preference = MetalinkResource::getLowestPriority();
-        }
+      }
+      else if(util::parseIntNoThrow(preference, std::string((*itr).value, (*itr).valueLength)) &&
+              preference >= 0) {
+        // In Metalink3Spec, highest prefernce value is 100.  We
+        // use Metalink4Spec priority unit system in which 1 is
+        // higest.
+        preference = 101-preference;
+      }
+      else {
+        preference = MetalinkResource::getLowestPriority();
       }
     }
     int maxConnections;
     {
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "maxconnections", METALINK3_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "maxconnections", METALINK3_NAMESPACE_URI);
       if(itr == attrs.end()) {
         maxConnections = -1;
-      } else {
-        if(!util::parseIntNoThrow
-           (maxConnections, std::string((*itr).value, (*itr).valueLength)) ||
-           maxConnections <= 0) {
-          maxConnections = -1;
-        }
+      } else if(!util::parseIntNoThrow(maxConnections, std::string((*itr).value, (*itr).valueLength)) ||
+                maxConnections <= 0) {
+        maxConnections = -1;
       }
     }
     psm->newResourceTransaction();

+ 43 - 61
src/MetalinkParserStateV4Impl.cc

@@ -60,24 +60,24 @@ void MetalinkMetalinkParserStateV4::beginElement
  const char* nsUri,
  const std::vector<XmlAttr>& attrs)
 {
-  if(checkNsUri(nsUri) && strcmp(localname, "file") == 0) {
-    psm->setFileStateV4();
-    std::vector<XmlAttr>::const_iterator itr =
-      findAttr(attrs, "name", METALINK4_NAMESPACE_URI);
-    if(itr == attrs.end() || (*itr).valueLength == 0) {
-      psm->logError("Missing file@name");
-      return;
-    }
-    std::string name((*itr).value, (*itr).valueLength);
-    if(util::detectDirTraversal(name)) {
-      psm->logError("Bad file@name");
-      return;
-    }
-    psm->newEntryTransaction();
-    psm->setFileNameOfEntry(name);
-  } else {
+  if(checkNsUri(nsUri) && strcmp(localname, "file") != 0) {
     psm->setSkipTagState();
+    return;
+  }
+
+  psm->setFileStateV4();
+  auto itr = findAttr(attrs, "name", METALINK4_NAMESPACE_URI);
+  if(itr == attrs.end() || (*itr).valueLength == 0) {
+    psm->logError("Missing file@name");
+    return;
+  }
+  std::string name((*itr).value, (*itr).valueLength);
+  if(util::detectDirTraversal(name)) {
+    psm->logError("Bad file@name");
+    return;
   }
+  psm->newEntryTransaction();
+  psm->setFileNameOfEntry(name);
 }
 
 void FileMetalinkParserStateV4::beginElement
@@ -101,8 +101,7 @@ void FileMetalinkParserStateV4::beginElement
     psm->setMetaurlStateV4();
     std::string name;
     {
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "name", METALINK4_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "name", METALINK4_NAMESPACE_URI);
       if(itr != attrs.end()) {
         name.assign((*itr).value, (*itr).valueLength);
         if(name.empty() || util::detectDirTraversal(name)) {
@@ -113,33 +112,27 @@ void FileMetalinkParserStateV4::beginElement
     }
     int priority;
     {
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "priority", METALINK4_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "priority", METALINK4_NAMESPACE_URI);
       if(itr == attrs.end()) {
         priority = MetalinkResource::getLowestPriority();
-      } else {
-        if(util::parseIntNoThrow
-           (priority, std::string((*itr).value, (*itr).valueLength))) {
-          if(priority < 1 || MetalinkResource::getLowestPriority() < priority) {
-            psm->logError("metaurl@priority is out of range");
-            return;
-          }
-        } else {
-          psm->logError("Bad metaurl@priority");
+      } else if(util::parseIntNoThrow(priority, std::string((*itr).value, (*itr).valueLength))) {
+        if(priority < 1 || MetalinkResource::getLowestPriority() < priority) {
+          psm->logError("metaurl@priority is out of range");
           return;
         }
+      } else {
+        psm->logError("Bad metaurl@priority");
+        return;
       }
     }
     std::string mediatype;
     {
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "mediatype", METALINK4_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "mediatype", METALINK4_NAMESPACE_URI);
       if(itr == attrs.end() || (*itr).valueLength == 0) {
         psm->logError("Missing metaurl@mediatype");
         return;
-      } else {
-        mediatype.assign((*itr).value, (*itr).valueLength);
       }
+      mediatype.assign((*itr).value, (*itr).valueLength);
     }
     psm->newMetaurlTransaction();
     psm->setPriorityOfMetaurl(priority);
@@ -149,29 +142,24 @@ void FileMetalinkParserStateV4::beginElement
     psm->setURLStateV4();
     std::string location;
     {
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "location", METALINK4_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "location", METALINK4_NAMESPACE_URI);
       if(itr != attrs.end()) {
         location.assign((*itr).value, (*itr).valueLength);
       }
     }
     int priority;
     {
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "priority", METALINK4_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "priority", METALINK4_NAMESPACE_URI);
       if(itr == attrs.end()) {
         priority = MetalinkResource::getLowestPriority();
-      } else {
-        if(util::parseIntNoThrow
-           (priority, std::string((*itr).value, (*itr).valueLength))) {
-          if(priority < 1 || MetalinkResource::getLowestPriority() < priority) {
-            psm->logError("url@priority is out of range");
-            return;
-          }
-        } else {
-          psm->logError("Bad url@priority");
+      } else if(util::parseIntNoThrow(priority, std::string((*itr).value, (*itr).valueLength))) {
+        if(priority < 1 || MetalinkResource::getLowestPriority() < priority) {
+          psm->logError("url@priority is out of range");
           return;
         }
+      } else {
+        psm->logError("Bad url@priority");
+        return;
       }
     }
     psm->newResourceTransaction();
@@ -181,40 +169,35 @@ void FileMetalinkParserStateV4::beginElement
 #ifdef ENABLE_MESSAGE_DIGEST
   else if(strcmp(localname, "hash") == 0) {
     psm->setHashStateV4();
-    std::vector<XmlAttr>::const_iterator itr =
-      findAttr(attrs, "type", METALINK4_NAMESPACE_URI);
+    auto itr = findAttr(attrs, "type", METALINK4_NAMESPACE_URI);
     if(itr == attrs.end() || (*itr).valueLength == 0) {
       psm->logError("Missing hash@type");
       return;
-    } else {
-      psm->newChecksumTransaction();
-      psm->setTypeOfChecksum(std::string((*itr).value, (*itr).valueLength));
     }
+    psm->newChecksumTransaction();
+    psm->setTypeOfChecksum(std::string((*itr).value, (*itr).valueLength));
   } else if(strcmp(localname, "pieces") == 0) {
     psm->setPiecesStateV4();
     uint32_t length;
     {
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "length", METALINK4_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "length", METALINK4_NAMESPACE_URI);
       if(itr == attrs.end() || (*itr).valueLength == 0) {
         psm->logError("Missing pieces@length");
         return;
-      } else if(!util::parseUIntNoThrow
-                (length, std::string((*itr).value, (*itr).valueLength))) {
+      }
+      if(!util::parseUIntNoThrow(length, std::string((*itr).value, (*itr).valueLength))) {
         psm->logError("Bad pieces@length");
         return;
       }
     }
     std::string type;
     {
-      std::vector<XmlAttr>::const_iterator itr =
-        findAttr(attrs, "type", METALINK4_NAMESPACE_URI);
+      auto itr = findAttr(attrs, "type", METALINK4_NAMESPACE_URI);
       if(itr == attrs.end() || (*itr).valueLength == 0) {
         psm->logError("Missing pieces@type");
         return;
-      } else {
-        type.assign((*itr).value, (*itr).valueLength);
       }
+      type.assign((*itr).value, (*itr).valueLength);
     }
     psm->newChunkChecksumTransactionV4();
     psm->setLengthOfChunkChecksumV4(length);
@@ -223,8 +206,7 @@ void FileMetalinkParserStateV4::beginElement
 #endif // ENABLE_MESSAGE_DIGEST
   else if(strcmp(localname, "signature") == 0) {
     psm->setSignatureStateV4();
-    std::vector<XmlAttr>::const_iterator itr =
-      findAttr(attrs, "mediatype", METALINK4_NAMESPACE_URI);
+    auto itr = findAttr(attrs, "mediatype", METALINK4_NAMESPACE_URI);
     if(itr == attrs.end() || (*itr).valueLength == 0) {
       psm->logError("Missing signature@mediatype");
       return;

+ 19 - 20
src/OptionHandlerImpl.cc

@@ -169,21 +169,22 @@ void NumberOptionHandler::parseArg(Option& option, int64_t number) const
 {
   if((min_ == -1 || min_ <= number) && (max_ ==  -1 || number <= max_)) {
     option.put(pref_, util::itos(number));
+    return;
+  }
+
+  std::string msg = pref_->k;
+  msg += " ";
+  if(min_ == -1 && max_ != -1) {
+    msg += fmt(_("must be smaller than or equal to %" PRId64 "."), max_);
+  } else if(min_ != -1 && max_ != -1) {
+    msg += fmt(_("must be between %" PRId64 " and %" PRId64 "."),
+                min_, max_);
+  } else if(min_ != -1 && max_ == -1) {
+    msg += fmt(_("must be greater than or equal to %" PRId64 "."), min_);
   } else {
-    std::string msg = pref_->k;
-    msg += " ";
-    if(min_ == -1 && max_ != -1) {
-      msg += fmt(_("must be smaller than or equal to %" PRId64 "."), max_);
-    } else if(min_ != -1 && max_ != -1) {
-      msg += fmt(_("must be between %" PRId64 " and %" PRId64 "."),
-                 min_, max_);
-    } else if(min_ != -1 && max_ == -1) {
-      msg += fmt(_("must be greater than or equal to %" PRId64 "."), min_);
-    } else {
-      msg += _("must be a number.");
-    }
-    throw DL_ABORT_EX(msg);
+    msg += _("must be a number.");
   }
+  throw DL_ABORT_EX(msg);
 }
 
 std::string NumberOptionHandler::createPossibleValuesString() const
@@ -405,20 +406,18 @@ ParameterOptionHandler::~ParameterOptionHandler() {}
 void ParameterOptionHandler::parseArg(Option& option, const std::string& optarg)
   const
 {
-  std::vector<std::string>::const_iterator itr =
-    std::find(validParamValues_.begin(), validParamValues_.end(), optarg);
+  auto itr = std::find(validParamValues_.begin(), validParamValues_.end(), optarg);
   if(itr == validParamValues_.end()) {
     std::string msg = pref_->k;
     msg += " ";
     msg += _("must be one of the following:");
     if(validParamValues_.size() == 0) {
       msg += "''";
-    } else {
-      for(std::vector<std::string>::const_iterator itr =
-            validParamValues_.begin(), eoi = validParamValues_.end();
-          itr != eoi; ++itr) {
+    }
+    else {
+      for (const auto& p: validParamValues_) {
         msg += "'";
-        msg += *itr;
+        msg += p;
         msg += "' ";
       }
     }

+ 17 - 22
src/OptionParser.cc

@@ -262,9 +262,8 @@ void OptionParser::parse(Option& option, const KeyVals& options) const
 void OptionParser::setOptionHandlers
 (const std::vector<OptionHandler*>& handlers)
 {
-  for(std::vector<OptionHandler*>::const_iterator i =
-        handlers.begin(), eoi = handlers.end(); i != eoi; ++i) {
-    addOptionHandler(*i);
+  for (const auto& h: handlers) {
+    addOptionHandler(h);
   }
 }
 
@@ -280,10 +279,9 @@ void OptionParser::addOptionHandler(OptionHandler* handler)
 
 void OptionParser::parseDefaultValues(Option& option) const
 {
-  for(std::vector<OptionHandler*>::const_iterator i =
-        handlers_.begin(), eoi = handlers_.end(); i != eoi; ++i) {
-    if(*i && !(*i)->getDefaultValue().empty()) {
-      (*i)->parse(option, (*i)->getDefaultValue());
+  for (const auto& h: handlers_) {
+    if (h && !h->getDefaultValue().empty()) {
+      h->parse(option, h->getDefaultValue());
     }
   }
 }
@@ -291,10 +289,9 @@ void OptionParser::parseDefaultValues(Option& option) const
 std::vector<const OptionHandler*> OptionParser::findByTag(uint32_t tag) const
 {
   std::vector<const OptionHandler*> result;
-  for(std::vector<OptionHandler*>::const_iterator i =
-        handlers_.begin(), eoi = handlers_.end(); i != eoi; ++i) {
-    if(*i && !(*i)->isHidden() && (*i)->hasTag(tag)) {
-      result.push_back(*i);
+  for (const auto& h: handlers_) {
+    if(h && !h->isHidden() && h->hasTag(tag)) {
+      result.push_back(h);
     }
   }
   return result;
@@ -304,14 +301,13 @@ std::vector<const OptionHandler*>
 OptionParser::findByNameSubstring(const std::string& substring) const
 {
   std::vector<const OptionHandler*> result;
-  for(std::vector<OptionHandler*>::const_iterator i =
-        handlers_.begin(), eoi = handlers_.end(); i != eoi; ++i) {
-    if(*i && !(*i)->isHidden()) {
-      size_t nameLen = strlen((*i)->getName());
-      if(std::search((*i)->getName(), (*i)->getName()+nameLen,
+  for (const auto& h: handlers_) {
+    if(h && !h->isHidden()) {
+      size_t nameLen = strlen(h->getName());
+      if(std::search(h->getName(), h->getName()+nameLen,
                      substring.begin(), substring.end()) !=
-         (*i)->getName()+nameLen) {
-        result.push_back(*i);
+         h->getName()+nameLen) {
+        result.push_back(h);
       }
     }
   }
@@ -321,10 +317,9 @@ OptionParser::findByNameSubstring(const std::string& substring) const
 std::vector<const OptionHandler*> OptionParser::findAll() const
 {
   std::vector<const OptionHandler*> result;
-  for(std::vector<OptionHandler*>::const_iterator i =
-        handlers_.begin(), eoi = handlers_.end(); i != eoi; ++i) {
-    if(*i && !(*i)->isHidden()) {
-      result.push_back(*i);
+  for (const auto& h: handlers_) {
+    if(h && !h->isHidden()) {
+      result.push_back(h);
     }
   }
   return result;

+ 1 - 1
src/PeerConnection.cc

@@ -274,7 +274,7 @@ void PeerConnection::reserveBuffer(size_t minSize)
 {
   if(bufferCapacity_ < minSize) {
     bufferCapacity_ = minSize;
-    unsigned char *buf = new unsigned char[bufferCapacity_];
+    auto buf = new unsigned char[bufferCapacity_];
     memcpy(buf, resbuf_, resbufLength_);
     delete [] resbuf_;
     resbuf_ = buf;

+ 1 - 1
src/Piece.cc

@@ -362,7 +362,7 @@ void Piece::updateWrCache(WrDiskCache* diskCache, unsigned char* data,
   }
   assert(wrCache_);
   A2_LOG_DEBUG(fmt("updateWrCache entry=%p", wrCache_));
-  WrDiskCacheEntry::DataCell* cell = new WrDiskCacheEntry::DataCell();
+  auto cell = new WrDiskCacheEntry::DataCell();
   cell->goff = goff;
   cell->data = data;
   cell->offset = offset;

+ 1 - 1
src/PollEventPoll.cc

@@ -168,7 +168,7 @@ bool PollEventPoll::addEvents
     event.addSelf(socketEntry);
     if(pollfdCapacity_ == pollfdNum_) {
       pollfdCapacity_ *= 2;
-      struct pollfd* newPollfds = new struct pollfd[pollfdCapacity_];
+      auto newPollfds = new struct pollfd[pollfdCapacity_];
       memcpy(newPollfds, pollfds_, pollfdNum_*sizeof(struct pollfd));
       delete [] pollfds_;
       pollfds_ = newPollfds;

+ 2 - 2
src/PriorityPieceSelector.cc

@@ -44,8 +44,8 @@ PriorityPieceSelector::PriorityPieceSelector
 bool PriorityPieceSelector::select
 (size_t& index, const unsigned char* bitfield, size_t nbits) const
 {
-  for(std::vector<size_t>::const_iterator i = prioritizedPieces_.begin(),
-        eoi = prioritizedPieces_.end(); i != eoi; ++i) {
+  for(auto i = prioritizedPieces_.begin(), eoi = prioritizedPieces_.end();
+      i != eoi; ++i) {
     if(bitfield::test(bitfield, nbits, *i)) {
       index = *i;
       return true;

+ 1 - 1
src/RangeBtMessage.cc

@@ -57,7 +57,7 @@ unsigned char* RangeBtMessage::createMessage()
    * length -- length, 4bytes
    * total: 17bytes
    */
-  unsigned char* msg = new unsigned char[MESSAGE_LENGTH];
+  auto msg = new unsigned char[MESSAGE_LENGTH];
   bittorrent::createPeerMessageString(msg, MESSAGE_LENGTH, 13, getId());
   bittorrent::setIntParam(&msg[5], index_);
   bittorrent::setIntParam(&msg[9], begin_);

+ 3 - 3
src/RequestGroup.cc

@@ -330,7 +330,7 @@ void RequestGroup::createInitialCommand
         progressInfoFilePtr->setBtRuntime(btRuntime);
       }
 
-      DefaultPeerStorage* peerStoragePtr(new DefaultPeerStorage());
+      auto peerStoragePtr(new DefaultPeerStorage());
       peerStoragePtr->setBtRuntime(btRuntime);
       peerStoragePtr->setPieceStorage(pieceStorage_);
       peerStorage_ = peerStoragePtr;
@@ -574,7 +574,7 @@ void RequestGroup::initPieceStorage()
 #endif // ENABLE_BITTORRENT
       )) {
 #ifdef ENABLE_BITTORRENT
-    DefaultPieceStorage* ps =
+    auto ps =
       new DefaultPieceStorage(downloadContext_, option_.get());
     std::shared_ptr<PieceStorage> psHolder(ps);
     if(downloadContext_->hasAttribute(CTX_ATTR_BT)) {
@@ -616,7 +616,7 @@ void RequestGroup::initPieceStorage()
     }
     tempPieceStorage.swap(psHolder);
   } else {
-    UnknownLengthPieceStorage* ps =
+    auto ps =
       new UnknownLengthPieceStorage(downloadContext_);
     std::shared_ptr<PieceStorage> psHolder(ps);
     if(diskWriterFactory_) {

+ 27 - 39
src/RequestGroupMan.cc

@@ -279,17 +279,16 @@ private:
         group->getSegmentMan()->getPeerStats().size() == 1;
       const std::vector<std::shared_ptr<PeerStat> >& peerStats =
         group->getSegmentMan()->getFastestPeerStats();
-      for(std::vector<std::shared_ptr<PeerStat> >::const_iterator i =
-            peerStats.begin(), eoi = peerStats.end(); i != eoi; ++i) {
-        if((*i)->getHostname().empty() || (*i)->getProtocol().empty()) {
+      for(auto & stat : peerStats) {
+        if(stat->getHostname().empty() || stat->getProtocol().empty()) {
           continue;
         }
-        int speed = (*i)->getAvgDownloadSpeed();
+        int speed = stat->getAvgDownloadSpeed();
         if (speed == 0) continue;
 
         std::shared_ptr<ServerStat> ss =
-          e_->getRequestGroupMan()->getOrCreateServerStat((*i)->getHostname(),
-                                                          (*i)->getProtocol());
+          e_->getRequestGroupMan()->getOrCreateServerStat(stat->getHostname(),
+                                                          stat->getProtocol());
         ss->increaseCounter();
         ss->updateDownloadSpeed(speed);
         if(singleConnection) {
@@ -361,14 +360,13 @@ public:
                             GroupId::toHex(group->getGID()).c_str()));
             const std::vector<std::shared_ptr<FileEntry> >& files =
               dctx->getFileEntries();
-            for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
-                  files.begin(), eoi = files.end(); i != eoi; ++i) {
-              if(!(*i)->isRequested()) {
-                if(File((*i)->getPath()).remove()) {
-                  A2_LOG_INFO(fmt(MSG_FILE_REMOVED, (*i)->getPath().c_str()));
+            for(auto & file : files) {
+              if(!file->isRequested()) {
+                if(File(file->getPath()).remove()) {
+                  A2_LOG_INFO(fmt(MSG_FILE_REMOVED, file->getPath().c_str()));
                 } else {
                   A2_LOG_INFO(fmt(MSG_FILE_COULD_NOT_REMOVED,
-                                  (*i)->getPath().c_str()));
+                                  file->getPath().c_str()));
                 }
               }
             }
@@ -535,9 +533,8 @@ void RequestGroupMan::save()
 
 void RequestGroupMan::closeFile()
 {
-  for(RequestGroupList::iterator itr = requestGroups_.begin(),
-        eoi = requestGroups_.end(); itr != eoi; ++itr) {
-    (*itr)->closeFile();
+  for(auto & elem : requestGroups_) {
+    elem->closeFile();
   }
 }
 
@@ -548,10 +545,8 @@ RequestGroupMan::DownloadStat RequestGroupMan::getDownloadStat() const
   int inprogress = 0;
   int removed = 0;
   error_code::Value lastError = removedLastErrorResult_;
-  for(DownloadResultList::const_iterator itr =
-        downloadResults_.begin(), eoi = downloadResults_.end(); itr != eoi;
-      ++itr) {
-    const std::shared_ptr<DownloadResult>& dr = *itr;
+  for(auto & dr : downloadResults_) {
+
     if(dr->belongsTo != 0) {
       continue;
     }
@@ -637,10 +632,8 @@ void RequestGroupMan::showDownloadResults(OutputFile& o, bool full) const
   int err = 0;
   int inpr = 0;
   int rm = 0;
-  for(DownloadResultList::const_iterator itr =
-        downloadResults_.begin(), eoi = downloadResults_.end(); itr != eoi;
-      ++itr) {
-    const std::shared_ptr<DownloadResult>& dr = *itr;
+  for(auto & dr : downloadResults_) {
+
     if(dr->belongsTo != 0) {
       continue;
     }
@@ -719,9 +712,8 @@ void RequestGroupMan::formatDownloadResultFull
   bool head = true;
   const std::vector<std::shared_ptr<FileEntry> >& fileEntries =
     downloadResult->fileEntries;
-  for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
-        fileEntries.begin(), eoi = fileEntries.end(); i != eoi; ++i) {
-    if(!(*i)->isRequested()) {
+  for(auto & f: fileEntries) {
+    if(!f->isRequested()) {
       continue;
     }
     std::stringstream o;
@@ -731,14 +723,14 @@ void RequestGroupMan::formatDownloadResultFull
     } else {
       o << "   |    |           |";
     }
-    if((*i)->getLength() == 0 || downloadResult->bitfield.empty()) {
+    if(f->getLength() == 0 || downloadResult->bitfield.empty()) {
       o << "  -|";
     } else {
       int64_t completedLength =
-        bt.getOffsetCompletedLength((*i)->getOffset(), (*i)->getLength());
-      o << std::setw(3) << 100*completedLength/(*i)->getLength() << "|";
+        bt.getOffsetCompletedLength(f->getOffset(), f->getLength());
+      o << std::setw(3) << 100*completedLength/f->getLength() << "|";
     }
-    writeFilePath(o, *i, downloadResult->inMemoryDownload);
+    writeFilePath(o, f, downloadResult->inMemoryDownload);
     o << "\n";
     out.write(o.str().c_str());
   }
@@ -787,9 +779,7 @@ bool RequestGroupMan::isSameFileBeingDownloaded(RequestGroup* requestGroup) cons
     return false;
   }
   std::vector<std::string> files;
-  for(RequestGroupList::const_iterator itr = requestGroups_.begin(),
-        eoi = requestGroups_.end(); itr != eoi; ++itr) {
-    const std::shared_ptr<RequestGroup>& rg = *itr;
+  for(auto & rg : requestGroups_) {
     if(rg.get() != requestGroup) {
       const std::vector<std::shared_ptr<FileEntry> >& entries =
         rg->getDownloadContext()->getFileEntries();
@@ -807,17 +797,15 @@ bool RequestGroupMan::isSameFileBeingDownloaded(RequestGroup* requestGroup) cons
 
 void RequestGroupMan::halt()
 {
-  for(RequestGroupList::const_iterator i = requestGroups_.begin(),
-        eoi = requestGroups_.end(); i != eoi; ++i) {
-    (*i)->setHaltRequested(true);
+  for(auto & elem : requestGroups_) {
+    elem->setHaltRequested(true);
   }
 }
 
 void RequestGroupMan::forceHalt()
 {
-  for(RequestGroupList::const_iterator i = requestGroups_.begin(),
-        eoi = requestGroups_.end(); i != eoi; ++i) {
-    (*i)->setForceHaltRequested(true);
+  for(auto & elem : requestGroups_) {
+    elem->setForceHaltRequested(true);
   }
 }
 

+ 2 - 3
src/RpcMethod.cc

@@ -102,9 +102,8 @@ void gatherOption
       // header and index-out option can take array as value
       const List* oplist = downcast<List>((*first).second);
       if(oplist) {
-        for(List::ValueType::const_iterator argiter = oplist->begin(),
-              eoi = oplist->end(); argiter != eoi; ++argiter) {
-          const String* opval = downcast<String>(*argiter);
+        for(auto & elem : *oplist) {
+          const String* opval = downcast<String>(elem);
           if(opval) {
             handler->parse(*option, opval->s());
           }

+ 12 - 17
src/RpcMethodImpl.cc

@@ -212,9 +212,8 @@ template<typename OutputIterator>
 void extractUris(OutputIterator out, const List* src)
 {
   if(src) {
-    for(List::ValueType::const_iterator i = src->begin(), eoi = src->end();
-        i != eoi; ++i) {
-      const String* uri = downcast<String>(*i);
+    for(auto & elem : *src) {
+      const String* uri = downcast<String>(elem);
       if(uri) {
         out++ = uri->s();
       }
@@ -1272,27 +1271,24 @@ std::unique_ptr<ValueBase> ChangeUriRpcMethod::process
   }
   auto& s = files[index];
   size_t delcount = 0;
-  for(auto i = delUrisParam->begin(), eoi = delUrisParam->end();
-      i != eoi; ++i) {
-    const String* uri = downcast<String>(*i);
+  for(auto & elem : *delUrisParam) {
+    const String* uri = downcast<String>(elem);
     if(uri && s->removeUri(uri->s())) {
       ++delcount;
     }
   }
   size_t addcount = 0;
   if(posGiven) {
-    for(auto i = addUrisParam->begin(), eoi = addUrisParam->end();
-        i != eoi; ++i) {
-      const String* uri = downcast<String>(*i);
+    for(auto & elem : *addUrisParam) {
+      const String* uri = downcast<String>(elem);
       if(uri && s->insertUri(uri->s(), pos)) {
         ++addcount;
         ++pos;
       }
     }
   } else {
-    for(auto i = addUrisParam->begin(), eoi = addUrisParam->end();
-        i != eoi; ++i) {
-      const String* uri = downcast<String>(*i);
+    for(auto & elem : *addUrisParam) {
+      const String* uri = downcast<String>(elem);
       if(uri && s->addUri(uri->s())) {
         ++addcount;
       }
@@ -1354,8 +1350,8 @@ std::unique_ptr<ValueBase> SystemMulticallRpcMethod::process
 {
   const List* methodSpecs = checkRequiredParam<List>(req, 0);
   auto list = List::g();
-  for(auto i = methodSpecs->begin(), eoi = methodSpecs->end(); i != eoi; ++i) {
-    Dict* methodDict = downcast<Dict>(*i);
+  for(auto & methodSpec : *methodSpecs) {
+    Dict* methodDict = downcast<Dict>(methodSpec);
     if(!methodDict) {
       list->append(createErrorResponse
                    (DL_ABORT_EX("system.multicall expected struct."), req));
@@ -1453,9 +1449,8 @@ void changeOption
   if(option.defined(PREF_MAX_CONNECTION_PER_SERVER)) {
     int maxConn = grOption->getAsInt(PREF_MAX_CONNECTION_PER_SERVER);
     const std::vector<std::shared_ptr<FileEntry> >& files = dctx->getFileEntries();
-    for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i = files.begin(),
-          eoi = files.end(); i != eoi; ++i) {
-      (*i)->setMaxConnectionPerServer(maxConn);
+    for(auto & file : files) {
+      (file)->setMaxConnectionPerServer(maxConn);
     }
   }
   if(option.defined(PREF_DIR) || option.defined(PREF_OUT)) {

+ 2 - 3
src/RpcMethodImpl.h

@@ -116,9 +116,8 @@ void toStringList(OutputIterator out, const List* src)
   if(!src) {
     return;
   }
-  for(List::ValueType::const_iterator i = src->begin(), eoi = src->end();
-      i != eoi; ++i) {
-    const String* s = downcast<String>(*i);
+  for(auto & elem : *src) {
+    const String* s = downcast<String>(elem);
     if(s) {
       *out++ = s->s();
     }

+ 5 - 9
src/SegmentMan.cc

@@ -164,8 +164,7 @@ std::shared_ptr<Segment> SegmentMan::checkoutSegment
                    segment->getWrittenLength()));
 
   if(piece->getLength() > 0) {
-    std::map<size_t, int32_t>::iterator positr =
-      segmentWrittenLengthMemo_.find(segment->getIndex());
+    auto positr = segmentWrittenLengthMemo_.find(segment->getIndex());
     if(positr != segmentWrittenLengthMemo_.end()) {
       const int32_t writtenLength = (*positr).second;
       A2_LOG_DEBUG(fmt("writtenLength(in memo)=%d, writtenLength=%d",
@@ -332,8 +331,7 @@ void SegmentMan::cancelSegment
 
 void SegmentMan::cancelAllSegments()
 {
-  for(std::deque<std::shared_ptr<SegmentEntry> >::iterator itr =
-        usedSegmentEntries_.begin(), eoi = usedSegmentEntries_.end();
+  for(auto itr = usedSegmentEntries_.begin(), eoi = usedSegmentEntries_.end();
       itr != eoi; ++itr) {
     cancelSegmentInternal((*itr)->cuid, (*itr)->segment);
   }
@@ -393,8 +391,7 @@ void SegmentMan::registerPeerStat(const std::shared_ptr<PeerStat>& peerStat)
 
 std::shared_ptr<PeerStat> SegmentMan::getPeerStat(cuid_t cuid) const
 {
-  for(std::vector<std::shared_ptr<PeerStat> >::const_iterator i =
-        peerStats_.begin(), eoi = peerStats_.end(); i != eoi; ++i) {
+  for(auto i = peerStats_.begin(), eoi = peerStats_.end(); i != eoi; ++i) {
     if((*i)->getCuid() == cuid) {
       return *i;
     }
@@ -420,9 +417,8 @@ public:
 
 void SegmentMan::updateFastestPeerStat(const std::shared_ptr<PeerStat>& peerStat)
 {
-  std::vector<std::shared_ptr<PeerStat> >::iterator i =
-    std::find_if(fastestPeerStats_.begin(), fastestPeerStats_.end(),
-                 PeerStatHostProtoEqual(peerStat));
+  auto i = std::find_if(fastestPeerStats_.begin(), fastestPeerStats_.end(),
+                        PeerStatHostProtoEqual(peerStat));
   if(i == fastestPeerStats_.end()) {
     fastestPeerStats_.push_back(peerStat);
   } else if((*i)->getAvgDownloadSpeed() < peerStat->getAvgDownloadSpeed()) {

+ 2 - 6
src/SelectEventPoll.cc

@@ -79,9 +79,7 @@ void SelectEventPoll::SocketEntry::addCommandEvent
 (Command* command, int events)
 {
   CommandEvent cev(command, events);
-  std::deque<CommandEvent>::iterator i = std::find(commandEvents_.begin(),
-                                                   commandEvents_.end(),
-                                                   cev);
+  auto i = std::find(commandEvents_.begin(), commandEvents_.end(), cev);
   if(i == commandEvents_.end()) {
     commandEvents_.push_back(cev);
   } else {
@@ -92,9 +90,7 @@ void SelectEventPoll::SocketEntry::removeCommandEvent
 (Command* command, int events)
 {
   CommandEvent cev(command, events);
-  std::deque<CommandEvent>::iterator i = std::find(commandEvents_.begin(),
-                                                   commandEvents_.end(),
-                                                   cev);
+  auto i = std::find(commandEvents_.begin(), commandEvents_.end(), cev);
   if(i == commandEvents_.end()) {
     // not found
   } else {

+ 1 - 1
src/SinkStreamFilter.cc

@@ -80,7 +80,7 @@ ssize_t SinkStreamFilter::transform
       if(alen < wlen) {
         size_t len = wlen - alen;
         size_t capacity = std::max(len, static_cast<size_t>(4096));
-        unsigned char* dataCopy = new unsigned char[capacity];
+        auto dataCopy = new unsigned char[capacity];
         memcpy(dataCopy, inbuf + alen, len);
         piece->updateWrCache(wrDiskCache_, dataCopy, 0, len, capacity,
                              segment->getPositionToWrite() + alen);

+ 2 - 4
src/SocketCore.cc

@@ -1194,8 +1194,7 @@ bool verifyHostname(const std::string& hostname,
     if(addrLen == 0) {
       return false;
     }
-    for(std::vector<std::string>::const_iterator i = ipAddrs.begin(),
-          eoi = ipAddrs.end(); i != eoi; ++i) {
+    for(auto i = ipAddrs.begin(), eoi = ipAddrs.end(); i != eoi; ++i) {
       if(addrLen == (*i).size() &&
          memcmp(binAddr, (*i).c_str(), addrLen) == 0) {
         return true;
@@ -1205,8 +1204,7 @@ bool verifyHostname(const std::string& hostname,
     if(dnsNames.empty()) {
       return util::tlsHostnameMatch(commonName, hostname);
     }
-    for(std::vector<std::string>::const_iterator i = dnsNames.begin(),
-          eoi = dnsNames.end(); i != eoi; ++i) {
+    for(auto i = dnsNames.begin(), eoi = dnsNames.end(); i != eoi; ++i) {
       if(util::tlsHostnameMatch(*i, hostname)) {
         return true;
       }

+ 4 - 7
src/StreamFileAllocationEntry.cc

@@ -73,13 +73,10 @@ void StreamFileAllocationEntry::prepareForNextAction
       getRequestGroup()->getDownloadContext();
     const std::vector<std::shared_ptr<FileEntry> >& fileEntries =
       dctx->getFileEntries();
-    for(std::vector<std::shared_ptr<FileEntry> >::const_iterator i =
-          fileEntries.begin(), eoi = fileEntries.end(); i != eoi; ++i) {
-      const FileEntry::InFlightRequestSet& reqs =
-        (*i)->getInFlightRequests();
-      for(FileEntry::InFlightRequestSet::iterator j =
-            reqs.begin(), eoj = reqs.end(); j != eoj; ++j) {
-        const std::shared_ptr<PeerStat>& peerStat = (*j)->getPeerStat();
+    for(auto & f : fileEntries) {
+      const auto& reqs = f->getInFlightRequests();
+      for(auto & req : reqs) {
+        const std::shared_ptr<PeerStat>& peerStat = req->getPeerStat();
         if(peerStat) {
           peerStat->downloadStart();
         }

+ 3 - 5
src/UDPTrackerClient.cc

@@ -452,8 +452,8 @@ std::shared_ptr<UDPTrackerRequest> UDPTrackerClient::findInflightRequest
  bool remove)
 {
   std::shared_ptr<UDPTrackerRequest> res;
-  for(std::deque<std::shared_ptr<UDPTrackerRequest> >::iterator i =
-        inflightRequests_.begin(), eoi = inflightRequests_.end(); i != eoi;
+  for(auto i = inflightRequests_.begin(), eoi = inflightRequests_.end();
+      i != eoi;
       ++i) {
     if((*i)->remoteAddr == remoteAddr && (*i)->remotePort == remotePort &&
        (*i)->transactionId == transactionId) {
@@ -470,9 +470,7 @@ std::shared_ptr<UDPTrackerRequest> UDPTrackerClient::findInflightRequest
 UDPTrackerConnection* UDPTrackerClient::getConnectionId
 (const std::string& remoteAddr, uint16_t remotePort, const Timer& now)
 {
-  std::map<std::pair<std::string, uint16_t>,
-           UDPTrackerConnection>::iterator i =
-    connectionIdCache_.find(std::make_pair(remoteAddr, remotePort));
+  auto i = connectionIdCache_.find(std::make_pair(remoteAddr, remotePort));
   if(i == connectionIdCache_.end()) {
     return nullptr;
   }

+ 3 - 5
src/UTMetadataRequestTracker.cc

@@ -57,9 +57,8 @@ bool UTMetadataRequestTracker::tracks(size_t index)
 
 void UTMetadataRequestTracker::remove(size_t index)
 {
-  std::vector<RequestEntry>::iterator i =
-    std::find(trackedRequests_.begin(), trackedRequests_.end(),
-              RequestEntry(index));
+  auto i = std::find(trackedRequests_.begin(), trackedRequests_.end(),
+                     RequestEntry(index));
   if(i != trackedRequests_.end()) {
     trackedRequests_.erase(i);
   }
@@ -109,8 +108,7 @@ size_t UTMetadataRequestTracker::avail() const
 std::vector<size_t> UTMetadataRequestTracker::getAllTrackedIndex() const
 {
   std::vector<size_t> indexes;
-  for(std::vector<RequestEntry>::const_iterator i = trackedRequests_.begin(),
-        eoi = trackedRequests_.end(); i != eoi; ++i) {
+  for(auto i = trackedRequests_.begin(), eoi = trackedRequests_.end(); i != eoi; ++i) {
     indexes.push_back((*i).index_);
   }
   return indexes;

+ 1 - 1
src/UnknownLengthPieceStorage.cc

@@ -57,7 +57,7 @@ UnknownLengthPieceStorage::~UnknownLengthPieceStorage() {}
 
 void UnknownLengthPieceStorage::initStorage()
 {
-  DirectDiskAdaptor* directDiskAdaptor(new DirectDiskAdaptor());
+  auto directDiskAdaptor(new DirectDiskAdaptor());
   directDiskAdaptor->setTotalLength(downloadContext_->getTotalLength());
   directDiskAdaptor->setFileEntries(downloadContext_->getFileEntries().begin(),
                                     downloadContext_->getFileEntries().end());

+ 10 - 10
src/ValueBaseStructParserStateMachine.cc

@@ -43,25 +43,25 @@
 namespace aria2 {
 
 namespace {
-ValueValueBaseStructParserState* valueState =
+auto valueState =
   new ValueValueBaseStructParserState();
-DictValueBaseStructParserState* dictState =
+auto dictState =
   new DictValueBaseStructParserState();
-DictKeyValueBaseStructParserState* dictKeyState =
+auto dictKeyState =
   new DictKeyValueBaseStructParserState();
-DictDataValueBaseStructParserState* dictDataState =
+auto dictDataState =
   new DictDataValueBaseStructParserState();
-ArrayValueBaseStructParserState* arrayState =
+auto arrayState =
   new ArrayValueBaseStructParserState();
-ArrayDataValueBaseStructParserState* arrayDataState =
+auto arrayDataState =
   new ArrayDataValueBaseStructParserState();
-StringValueBaseStructParserState* stringState =
+auto stringState =
   new StringValueBaseStructParserState();
-NumberValueBaseStructParserState* numberState =
+auto numberState =
   new NumberValueBaseStructParserState();
-BoolValueBaseStructParserState* boolState =
+auto boolState =
   new BoolValueBaseStructParserState();
-NullValueBaseStructParserState* nullState =
+auto nullState =
   new NullValueBaseStructParserState();
 } // namespace
 

+ 16 - 32
src/XmlRpcRequestParserStateMachine.cc

@@ -41,53 +41,37 @@ namespace aria2 {
 namespace rpc {
 
 namespace {
-InitialXmlRpcRequestParserState*
-initialState = new InitialXmlRpcRequestParserState();
+auto initialState = new InitialXmlRpcRequestParserState();
 
-UnknownElementXmlRpcRequestParserState*
-unknownElementState = new UnknownElementXmlRpcRequestParserState();
+auto unknownElementState = new UnknownElementXmlRpcRequestParserState();
 
-MethodCallXmlRpcRequestParserState*
-methodCallState = new MethodCallXmlRpcRequestParserState();
+auto methodCallState = new MethodCallXmlRpcRequestParserState();
 
-MethodNameXmlRpcRequestParserState*
-methodNameState = new MethodNameXmlRpcRequestParserState();
+auto methodNameState = new MethodNameXmlRpcRequestParserState();
 
-ParamsXmlRpcRequestParserState*
-paramsState = new ParamsXmlRpcRequestParserState();
+auto paramsState = new ParamsXmlRpcRequestParserState();
 
-ParamXmlRpcRequestParserState*
-paramState = new ParamXmlRpcRequestParserState();
+auto paramState = new ParamXmlRpcRequestParserState();
 
-ValueXmlRpcRequestParserState*
-valueState = new ValueXmlRpcRequestParserState();
+auto valueState = new ValueXmlRpcRequestParserState();
 
-IntXmlRpcRequestParserState*
-intState = new IntXmlRpcRequestParserState();
+auto intState = new IntXmlRpcRequestParserState();
 
-StringXmlRpcRequestParserState*
-stringState = new StringXmlRpcRequestParserState();
+auto stringState = new StringXmlRpcRequestParserState();
 
-Base64XmlRpcRequestParserState*
-base64State = new Base64XmlRpcRequestParserState();
+auto base64State = new Base64XmlRpcRequestParserState();
 
-StructXmlRpcRequestParserState*
-structState = new StructXmlRpcRequestParserState();
+auto structState = new StructXmlRpcRequestParserState();
 
-MemberXmlRpcRequestParserState*
-memberState = new MemberXmlRpcRequestParserState();
+auto memberState = new MemberXmlRpcRequestParserState();
 
-NameXmlRpcRequestParserState*
-nameState = new NameXmlRpcRequestParserState();
+auto nameState = new NameXmlRpcRequestParserState();
 
-ArrayXmlRpcRequestParserState*
-arrayState =  new ArrayXmlRpcRequestParserState();
+auto arrayState =  new ArrayXmlRpcRequestParserState();
 
-DataXmlRpcRequestParserState*
-dataState = new DataXmlRpcRequestParserState();
+auto dataState = new DataXmlRpcRequestParserState();
 
-ArrayValueXmlRpcRequestParserState*
-arrayValueState = new ArrayValueXmlRpcRequestParserState();
+auto arrayValueState = new ArrayValueXmlRpcRequestParserState();
 } // namespace
 
 XmlRpcRequestParserStateMachine::XmlRpcRequestParserStateMachine():

+ 1 - 1
src/ZeroBtMessage.cc

@@ -48,7 +48,7 @@ unsigned char* ZeroBtMessage::createMessage()
    * id --- ?, 1byte
    * total: 5bytes
    */
-  unsigned char* msg = new unsigned char[MESSAGE_LENGTH];
+  auto msg = new unsigned char[MESSAGE_LENGTH];
   bittorrent::createPeerMessageString(msg, MESSAGE_LENGTH, 1, getId());
   return msg;
 }

+ 28 - 40
src/bittorrent_helper.cc

@@ -154,9 +154,8 @@ void extractUrlList
 
     virtual void visit(const List& v) CXX11_OVERRIDE
     {
-      for(List::ValueType::const_iterator itr = v.begin(), eoi = v.end();
-          itr != eoi; ++itr) {
-        const String* uri = downcast<String>(*itr);
+      for(auto & elem : v) {
+        const String* uri = downcast<String>(elem);
         if(uri) {
           std::string utf8Uri = util::encodeNonUtf8(uri->s());
           uris_.push_back(utf8Uri);
@@ -235,9 +234,8 @@ void extractFileEntries
     int64_t offset = 0;
     // multi-file mode
     torrent->mode = BT_FILE_MODE_MULTI;
-    for(List::ValueType::const_iterator itr = filesList->begin(),
-          eoi = filesList->end(); itr != eoi; ++itr) {
-      const Dict* fileDict = downcast<Dict>(*itr);
+    for(auto & f : *filesList) {
+      const Dict* fileDict = downcast<Dict>(f);
       if(!fileDict) {
         continue;
       }
@@ -267,11 +265,10 @@ void extractFileEntries
 
       std::vector<std::string> pathelem(pathList->size()+1);
       pathelem[0] = utf8Name;
-      std::vector<std::string>::iterator pathelemOutItr = pathelem.begin();
+      auto pathelemOutItr = pathelem.begin();
       ++pathelemOutItr;
-      for(List::ValueType::const_iterator itr = pathList->begin(),
-            eoi = pathList->end(); itr != eoi; ++itr) {
-        const String* elem = downcast<String>(*itr);
+      for(auto & p : *pathList) {
+        const String* elem = downcast<String>(p);
         if(elem) {
           (*pathelemOutItr++) = elem->s();
         } else {
@@ -315,12 +312,11 @@ void extractFileEntries
     // For each uri in urlList, if it ends with '/', then
     // concatenate name to it. Specification just says so.
     std::vector<std::string> uris;
-    for(std::vector<std::string>::const_iterator i = urlList.begin(),
-          eoi = urlList.end(); i != eoi; ++i) {
-      if(!(*i).empty() && (*i)[(*i).size()-1] == '/') {
-        uris.push_back((*i)+util::percentEncode(utf8Name));
+    for(auto & elem : urlList) {
+      if(!elem.empty() && elem[elem.size()-1] == '/') {
+        uris.push_back(elem+util::percentEncode(utf8Name));
       } else {
-        uris.push_back(*i);
+        uris.push_back(elem);
       }
     }
     std::shared_ptr<FileEntry> fileEntry
@@ -344,16 +340,14 @@ void extractAnnounce(TorrentAttribute* torrent, const Dict* rootDict)
 {
   const List* announceList = downcast<List>(rootDict->get(C_ANNOUNCE_LIST));
   if(announceList) {
-    for(List::ValueType::const_iterator tierIter = announceList->begin(),
-          eoi = announceList->end(); tierIter != eoi; ++tierIter) {
-      const List* tier = downcast<List>(*tierIter);
+    for(auto & elem : *announceList) {
+      const List* tier = downcast<List>(elem);
       if(!tier) {
         continue;
       }
       std::vector<std::string> ntier;
-      for(List::ValueType::const_iterator uriIter = tier->begin(),
-            eoi2 = tier->end(); uriIter != eoi2; ++uriIter) {
-        const String* uri = downcast<String>(*uriIter);
+      for(auto & t : *tier) {
+        const String* uri = downcast<String>(t);
         if(uri) {
           ntier.push_back(util::encodeNonUtf8(util::strip(uri->s())));
         }
@@ -378,9 +372,8 @@ void extractNodes(TorrentAttribute* torrent, const ValueBase* nodesListSrc)
 {
   const List* nodesList = downcast<List>(nodesListSrc);
   if(nodesList) {
-    for(List::ValueType::const_iterator i = nodesList->begin(),
-          eoi = nodesList->end(); i != eoi; ++i) {
-      const List* addrPairList = downcast<List>(*i);
+    for(auto & elem : *nodesList) {
+      const List* addrPairList = downcast<List>(elem);
       if(!addrPairList || addrPairList->size() != 2) {
         continue;
       }
@@ -942,9 +935,9 @@ std::unique_ptr<TorrentAttribute> parseMagnet(const std::string& magnet)
   }
   const List* trs = downcast<List>(r->get("tr"));
   if(trs) {
-    for(auto i = trs->begin(), eoi = trs->end(); i != eoi; ++i) {
+    for(auto & tr : *trs) {
       std::vector<std::string> tier;
-      tier.push_back(util::encodeNonUtf8(downcast<String>(*i)->s()));
+      tier.push_back(util::encodeNonUtf8(downcast<String>(tr)->s()));
       attrs->announceList.push_back(tier);
     }
   }
@@ -973,10 +966,9 @@ std::string metadata2Torrent
   std::string torrent = "d";
 
   List announceList;
-  for(auto tierIter = attrs->announceList.begin(),
-        eoi = attrs->announceList.end(); tierIter != eoi; ++tierIter) {
+  for(auto & elem : attrs->announceList) {
     auto tier = List::g();
-    for(auto& uri : *tierIter) {
+    for(auto& uri : elem) {
       tier->append(uri);
     }
     if(!tier->empty()) {
@@ -1006,11 +998,9 @@ std::string torrent2Magnet(const TorrentAttribute* attrs)
     uri += "&dn=";
     uri += util::percentEncode(attrs->name);
   }
-  for(std::vector<std::vector<std::string> >::const_iterator tierIter =
-        attrs->announceList.begin(),
-        eoi = attrs->announceList.end(); tierIter != eoi; ++tierIter) {
-    for(std::vector<std::string>::const_iterator uriIter = (*tierIter).begin(),
-          eoi2 = (*tierIter).end(); uriIter != eoi2; ++uriIter) {
+  for(auto & elem : attrs->announceList) {
+    for(auto uriIter = elem.begin(),
+          eoi2 = elem.end(); uriIter != eoi2; ++uriIter) {
       uri += "&tr=";
       uri += util::percentEncode(*uriIter);
     }
@@ -1036,9 +1026,8 @@ void removeAnnounceUri
     return;
   }
   if(std::find(uris.begin(), uris.end(), "*") == uris.end()) {
-    for(std::vector<std::vector<std::string> >::iterator i =
-          attrs->announceList.begin(); i != attrs->announceList.end();) {
-      for(std::vector<std::string>::iterator j =(*i).begin();j != (*i).end();) {
+    for(auto i = attrs->announceList.begin(); i != attrs->announceList.end();) {
+      for(auto j = (*i).begin(); j != (*i).end();) {
         if(std::find(uris.begin(), uris.end(), *j) == uris.end()) {
           ++j;
         } else {
@@ -1059,10 +1048,9 @@ void removeAnnounceUri
 void addAnnounceUri
 (TorrentAttribute* attrs, const std::vector<std::string>& uris)
 {
-  for(std::vector<std::string>::const_iterator i = uris.begin(),
-        eoi = uris.end(); i != eoi; ++i) {
+  for(auto & uri : uris) {
     std::vector<std::string> tier;
-    tier.push_back(*i);
+    tier.push_back(uri);
     attrs->announceList.push_back(tier);
   }
 }

+ 4 - 6
src/bittorrent_helper.h

@@ -302,9 +302,8 @@ void extractPeer(const ValueBase* peerData, int family, OutputIterator dest)
 
     virtual void visit(const List& peerData) CXX11_OVERRIDE
     {
-      for(List::ValueType::const_iterator itr = peerData.begin(),
-            eoi = peerData.end(); itr != eoi; ++itr) {
-        const Dict* peerDict = downcast<Dict>(*itr);
+      for(auto & elem : peerData) {
+        const Dict* peerDict = downcast<Dict>(elem);
         if(!peerDict) {
           continue;
         }
@@ -354,9 +353,8 @@ void print(Output& o, const std::shared_ptr<DownloadContext>& dctx)
   for(std::vector<std::vector<std::string> >::const_iterator tierIter =
         torrentAttrs->announceList.begin(),
         eoi = torrentAttrs->announceList.end(); tierIter != eoi; ++tierIter) {
-    for(std::vector<std::string>::const_iterator i = (*tierIter).begin(),
-          eoi2 = (*tierIter).end(); i != eoi2; ++i) {
-      o.printf(" %s", (*i).c_str());
+    for(auto & elem : *tierIter) {
+      o.printf(" %s", elem.c_str());
     }
     o.write("\n");
   }

+ 2 - 2
src/option_processing.cc

@@ -168,8 +168,8 @@ void showCandidates
   global::cerr()->printf("\n");
   global::cerr()->printf(_("Did you mean:"));
   global::cerr()->printf("\n");
-  for(std::vector<std::pair<int, const Pref*> >::iterator i = cands.begin(),
-        eoi = cands.end(); i != eoi && (*i).first <= threshold; ++i) {
+  for(auto i = cands.begin(), eoi = cands.end();
+      i != eoi && (*i).first <= threshold; ++i) {
     global::cerr()->printf("\t--%s\n", (*i).second->k);
   }
 }

+ 2 - 3
src/paramed_string.h

@@ -221,9 +221,8 @@ void expand
   while(first != last) {
     InputIterator i = first;
     for(; i != last && *i != '{' && *i != '['; ++i);
-    for(std::vector<std::string>::iterator j = res.begin(), eoj = res.end();
-        j != eoj; ++j) {
-      (*j).append(first, i);
+    for(auto & re : res) {
+      re.append(first, i);
     }
     first = i;
     if(first == last) {

+ 3 - 3
src/prefs.cc

@@ -65,7 +65,7 @@ public:
   Pref* makePref(const char* key)
   {
     size_t id = nextId();
-    Pref* pref = new Pref(key, id);
+    auto pref = new Pref(key, id);
     i2p_.push_back(pref);
     k2p_[key] = pref;
     return pref;
@@ -81,7 +81,7 @@ public:
   }
   const Pref* k2p(const std::string& k) const
   {
-    std::map<std::string, const Pref*>::const_iterator i = k2p_.find(k);
+    auto i = k2p_.find(k);
     if(i == k2p_.end()) {
       return i2p_[0];
     } else {
@@ -96,7 +96,7 @@ private:
 
 PrefFactory* getPrefFactory()
 {
-  static PrefFactory* pf = new PrefFactory();
+  static auto pf = new PrefFactory();
   return pf;
 }
 

+ 2 - 4
src/util.cc

@@ -663,8 +663,7 @@ void computeHeadPieces
   if(head == 0) {
     return;
   }
-  for(std::vector<std::shared_ptr<FileEntry> >::const_iterator fi =
-        fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
+  for(auto fi = fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
     if((*fi)->getLength() == 0) {
       continue;
     }
@@ -688,8 +687,7 @@ void computeTailPieces
   if(tail == 0) {
     return;
   }
-  for(std::vector<std::shared_ptr<FileEntry> >::const_iterator fi =
-        fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
+  for(auto fi = fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
     if((*fi)->getLength() == 0) {
       continue;
     }

+ 1 - 1
src/wallclock.cc

@@ -40,7 +40,7 @@ namespace global {
 
 Timer& wallclock()
 {
-  static Timer* t = new Timer();
+  static auto t = new Timer();
   return *t;
 }