convert some for-loops into std algorithms

This commit is contained in:
arvidn 2018-11-26 15:16:39 +01:00 committed by Arvid Norberg
parent 3f87801142
commit 1b2832e018
14 changed files with 91 additions and 149 deletions

View File

@ -662,11 +662,8 @@ namespace {
namespace { namespace {
bool is_binary(std::string const& str) bool is_binary(std::string const& str)
{ {
for (char const c : str) return std::any_of(str.begin(), str.end()
{ , [](char const c) { return !is_print(c); });
if (!is_print(c)) return true;
}
return false;
} }
std::string print_string(std::string const& str) std::string print_string(std::string const& str)

View File

@ -537,12 +537,8 @@ int _System __libsocket_sysctl(int* mib, u_int namelen, void *oldp, size_t *oldl
bool in_local_network(std::vector<ip_interface> const& net, address const& addr) bool in_local_network(std::vector<ip_interface> const& net, address const& addr)
{ {
for (auto const& i : net) return std::any_of(net.begin(), net.end(), [&addr](ip_interface const& i)
{ { return match_addr_mask(addr, i.interface_address, i.netmask); });
if (match_addr_mask(addr, i.interface_address, i.netmask))
return true;
}
return false;
} }
std::vector<ip_interface> enum_net_interfaces(io_service& ios, error_code& ec) std::vector<ip_interface> enum_net_interfaces(io_service& ios, error_code& ec)
@ -1248,10 +1244,11 @@ int _System __libsocket_sysctl(int* mib, u_int namelen, void *oldp, size_t *oldl
std::string device_for_address(address addr, io_service& ios, error_code& ec) std::string device_for_address(address addr, io_service& ios, error_code& ec)
{ {
std::vector<ip_interface> ifs = enum_net_interfaces(ios, ec); std::vector<ip_interface> ifs = enum_net_interfaces(ios, ec);
if (ec) return std::string(); if (ec) return {};
for (auto const& iface : ifs) auto const iter = std::find_if(ifs.begin(), ifs.end()
if (iface.interface_address == addr) return iface.name; , [&addr](ip_interface const& iface)
return std::string(); { return iface.interface_address == addr; });
return (iter == ifs.end()) ? std::string() : iter->name;
} }
} }

View File

@ -186,15 +186,13 @@ namespace libtorrent {
void convert_path_to_posix(std::string& path) void convert_path_to_posix(std::string& path)
{ {
for (char& c : path) std::replace(path.begin(), path.end(), '\\', '/');
if (c == '\\') c = '/';
} }
#ifdef TORRENT_WINDOWS #ifdef TORRENT_WINDOWS
void convert_path_to_windows(std::string& path) void convert_path_to_windows(std::string& path)
{ {
for (char& c : path) std::replace(path.begin(), path.end(), '/', '\\');
if (c == '/') c = '\\';
} }
#endif #endif

View File

@ -1221,7 +1221,7 @@ void node::write_nodes_entries(sha1_hash const& info_hash
} }
} }
node::protocol_descriptor const& node::map_protocol_to_descriptor(udp protocol) node::protocol_descriptor const& node::map_protocol_to_descriptor(udp const protocol)
{ {
static std::array<protocol_descriptor, 2> const descriptors = static std::array<protocol_descriptor, 2> const descriptors =
{{ {{
@ -1229,14 +1229,16 @@ node::protocol_descriptor const& node::map_protocol_to_descriptor(udp protocol)
{udp::v6(), "n6", "nodes6"} {udp::v6(), "n6", "nodes6"}
}}; }};
for (auto const& d : descriptors) auto const iter = std::find_if(descriptors.begin(), descriptors.end()
, [&protocol](protocol_descriptor const& d) { return d.protocol == protocol; });
if (iter == descriptors.end())
{ {
if (d.protocol == protocol) TORRENT_ASSERT_FAIL();
return d; aux::throw_ex<std::out_of_range>("unknown protocol");
} }
TORRENT_ASSERT_FAIL(); return *iter;
aux::throw_ex<std::out_of_range>("unknown protocol");
} }
} } // namespace libtorrent::dht } } // namespace libtorrent::dht

View File

@ -177,10 +177,8 @@ std::tuple<int, int, int> routing_table::size() const
for (auto const& i : m_buckets) for (auto const& i : m_buckets)
{ {
nodes += int(i.live_nodes.size()); nodes += int(i.live_nodes.size());
for (auto const& k : i.live_nodes) confirmed += static_cast<int>(std::count_if(i.live_nodes.begin(), i.live_nodes.end()
{ , [](node_entry const& k) { return k.confirmed(); } ));
if (k.confirmed()) ++confirmed;
}
replacements += int(i.replacements.size()); replacements += int(i.replacements.size());
} }

View File

@ -79,39 +79,6 @@ namespace {
address const& m_addr; address const& m_addr;
std::uint16_t m_port; std::uint16_t m_port;
}; };
#if TORRENT_USE_INVARIANT_CHECKS
struct match_peer_connection
{
explicit match_peer_connection(peer_connection_interface const& c) : m_conn(c) {}
bool operator()(torrent_peer const* p) const
{
TORRENT_ASSERT(p->in_use);
return p->connection == &m_conn;
}
peer_connection_interface const& m_conn;
};
#endif
#if TORRENT_USE_ASSERTS
struct match_peer_connection_or_endpoint
{
explicit match_peer_connection_or_endpoint(peer_connection_interface const& c) : m_conn(c) {}
bool operator()(torrent_peer const* p) const
{
TORRENT_ASSERT(p->in_use);
return p->connection == &m_conn
|| (p->ip() == m_conn.remote()
&& p->connectable);
}
peer_connection_interface const& m_conn;
};
#endif
} }
namespace libtorrent { namespace libtorrent {
@ -1162,11 +1129,12 @@ namespace libtorrent {
// web seeds are special, they're not connected via the peer list // web seeds are special, they're not connected via the peer list
// so they're not kept in m_peers // so they're not kept in m_peers
TORRENT_ASSERT(p->web_seed TORRENT_ASSERT(p->web_seed
|| std::find_if( || std::any_of(m_peers.begin(), m_peers.end()
m_peers.begin() , [&c](torrent_peer const* tp)
, m_peers.end() {
, match_peer_connection(c)) TORRENT_ASSERT(tp->in_use);
!= m_peers.end()); return tp->connection == &c;
}));
#endif #endif
TORRENT_ASSERT(p->connection == &c); TORRENT_ASSERT(p->connection == &c);
@ -1224,10 +1192,8 @@ namespace libtorrent {
m_finished = state->is_finished; m_finished = state->is_finished;
m_max_failcount = state->max_failcount; m_max_failcount = state->max_failcount;
for (auto const& p : m_peers) m_num_connect_candidates += static_cast<int>(std::count_if(m_peers.begin(), m_peers.end()
{ , [this](torrent_peer const* p) { return this->is_connect_candidate(*p); } ));
m_num_connect_candidates += is_connect_candidate(*p);
}
#if TORRENT_USE_INVARIANT_CHECKS #if TORRENT_USE_INVARIANT_CHECKS
// the invariant is not likely to be upheld at the entry of this function // the invariant is not likely to be upheld at the entry of this function
@ -1244,17 +1210,19 @@ namespace libtorrent {
TORRENT_ASSERT(c); TORRENT_ASSERT(c);
iterator iter = std::lower_bound( iterator iter = std::lower_bound(m_peers.begin(), m_peers.end()
m_peers.begin(), m_peers.end()
, c->remote().address(), peer_address_compare()); , c->remote().address(), peer_address_compare());
if (iter != m_peers.end() && (*iter)->address() == c->remote().address()) if (iter != m_peers.end() && (*iter)->address() == c->remote().address())
return true; return true;
return std::find_if( return std::any_of(m_peers.begin(), m_peers.end()
m_peers.begin() , [c](torrent_peer const* p)
, m_peers.end() {
, match_peer_connection_or_endpoint(*c)) != m_peers.end(); TORRENT_ASSERT(p->in_use);
return p->connection == c
|| (p->ip() == c->remote() && p->connectable);
});
} }
#endif #endif

View File

@ -345,10 +345,8 @@ namespace libtorrent {
int piece_picker::get_download_queue_size() const int piece_picker::get_download_queue_size() const
{ {
int ret = 0; return std::accumulate(m_downloads.begin(), m_downloads.end(), 0
for (auto const& c : m_downloads) , [](int const acc, aux::vector<downloading_piece> const& q) { return acc + int(q.size()); });
ret += int(c.size());
return ret;
} }
void piece_picker::get_download_queue_sizes(int* partial void piece_picker::get_download_queue_sizes(int* partial

View File

@ -113,7 +113,7 @@ namespace libtorrent { namespace aux {
#else #else
// fallback // fallback
for (auto& b : buffer) b = char(random(0xff)); std::generate(buffer.begin(), buffer.end(), [] { return char(random(0xff)); });
#endif #endif
} }
} }

View File

@ -39,6 +39,7 @@ POSSIBILITY OF SUCH DAMAGE.
#include <cinttypes> // for PRId64 et.al. #include <cinttypes> // for PRId64 et.al.
#include <functional> #include <functional>
#include <type_traits> #include <type_traits>
#include <numeric> // for accumulate
#if TORRENT_USE_INVARIANT_CHECKS #if TORRENT_USE_INVARIANT_CHECKS
#include <unordered_set> #include <unordered_set>
@ -2906,15 +2907,9 @@ namespace aux {
// perform this check. // perform this check.
if (!m_settings.get_bool(settings_pack::incoming_starts_queued_torrents)) if (!m_settings.get_bool(settings_pack::incoming_starts_queued_torrents))
{ {
bool has_active_torrent = false; bool has_active_torrent = std::any_of(m_torrents.begin(), m_torrents.end()
for (auto& i : m_torrents) , [](std::pair<sha1_hash, std::shared_ptr<torrent>> const& i)
{ { return !i.second->is_torrent_paused(); });
if (!i.second->is_torrent_paused())
{
has_active_torrent = true;
break;
}
}
if (!has_active_torrent) if (!has_active_torrent)
{ {
#ifndef TORRENT_DISABLE_LOGGING #ifndef TORRENT_DISABLE_LOGGING
@ -5068,17 +5063,15 @@ namespace aux {
return bind_ep; return bind_ep;
} }
// verify that the interface ``addr`` belongs to, allows incoming connections // verify that ``addr``s interface allows incoming connections
bool session_impl::verify_incoming_interface(address const& addr) bool session_impl::verify_incoming_interface(address const& addr)
{ {
for (auto const& s : m_listen_sockets) auto const iter = std::find_if(m_listen_sockets.begin(), m_listen_sockets.end()
{ , [&addr](std::shared_ptr<listen_socket_t> const& s)
if (s->local_endpoint.address() == addr) { return s->local_endpoint.address() == addr; });
{ return iter == m_listen_sockets.end()
return s->incoming == duplex::accept_incoming; ? false
} : (*iter)->incoming == duplex::accept_incoming;
}
return false;
} }
// verify that the given local address satisfies the requirements of // verify that the given local address satisfies the requirements of
@ -5114,12 +5107,8 @@ namespace aux {
// if no device was found to have this address, we fail // if no device was found to have this address, we fail
if (device.empty()) return false; if (device.empty()) return false;
for (auto const& s : m_outgoing_interfaces) return std::any_of(m_outgoing_interfaces.begin(), m_outgoing_interfaces.end()
{ , [&device](std::string const& s) { return s == device; });
if (s == device) return true;
}
return false;
} }
void session_impl::remove_torrent(const torrent_handle& h void session_impl::remove_torrent(const torrent_handle& h
@ -5737,13 +5726,9 @@ namespace aux {
// this loop is potentially expensive. It could be optimized by // this loop is potentially expensive. It could be optimized by
// simply keeping a global counter // simply keeping a global counter
int peerlist_size = 0; s.peerlist_size = std::accumulate(m_torrents.begin(), m_torrents.end(), 0
for (auto const& i : m_torrents) , [](int const acc, std::pair<sha1_hash, std::shared_ptr<torrent>> const& t)
{ { return acc + t.second->num_known_peers(); });
peerlist_size += i.second->num_known_peers();
}
s.peerlist_size = peerlist_size;
return s; return s;
} }

View File

@ -36,6 +36,7 @@ POSSIBILITY OF SUCH DAMAGE.
#include <ctime> #include <ctime>
#include <algorithm> #include <algorithm>
#include <numeric>
#include <set> #include <set>
#include <functional> #include <functional>
#include <cstdio> #include <cstdio>
@ -803,15 +804,13 @@ namespace {
std::memset(b.data(), 0, std::size_t(b.size())); std::memset(b.data(), 0, std::size_t(b.size()));
ret += int(b.size()); ret += int(b.size());
} }
return 0; return ret;
} }
int writev(span<iovec_t const> bufs int writev(span<iovec_t const> bufs
, piece_index_t, int, open_mode_t, storage_error&) override , piece_index_t, int, open_mode_t, storage_error&) override
{ {
int ret = 0; return std::accumulate(bufs.begin(), bufs.end(), 0
for (auto const& b : bufs) , [](int const acc, iovec_t const& b) { return acc + int(b.size()); });
ret += int(b.size());
return 0;
} }
bool has_any_file(storage_error&) override { return false; } bool has_any_file(storage_error&) override { return false; }

View File

@ -137,8 +137,8 @@ namespace libtorrent {
"abcdefghijklmnopqrstuvwxyz-_.!~*()"; "abcdefghijklmnopqrstuvwxyz-_.!~*()";
// the random number // the random number
for (char& c : dest) std::generate(dest.begin(), dest.end()
c = printable[random(sizeof(printable) - 2)]; , []{ return printable[random(sizeof(printable) - 2)]; });
} }
bool string_ends_with(string_view s1, string_view s2) bool string_ends_with(string_view s1, string_view s2)

View File

@ -773,11 +773,8 @@ bool is_downloading_state(int const st)
if (m_trackers.empty()) return true; if (m_trackers.empty()) return true;
if (!settings().get_bool(settings_pack::use_dht_as_fallback)) return true; if (!settings().get_bool(settings_pack::use_dht_as_fallback)) return true;
int verified_trackers = 0; return std::none_of(m_trackers.begin(), m_trackers.end()
for (auto const& tr : m_trackers) , [](announce_entry const& tr) { return bool(tr.verified); });
if (tr.verified) ++verified_trackers;
return verified_trackers == 0;
} }
#endif #endif
@ -2566,9 +2563,9 @@ bool is_downloading_state(int const st)
if (settings().get_bool(settings_pack::use_dht_as_fallback)) if (settings().get_bool(settings_pack::use_dht_as_fallback))
{ {
int verified_trackers = 0; int const verified_trackers = static_cast<int>(std::count_if(
for (auto const& t : m_trackers) m_trackers.begin(), m_trackers.end()
if (t.verified) ++verified_trackers; , [](announce_entry const& t) { return t.verified; }));
if (verified_trackers > 0) if (verified_trackers > 0)
debug_log("DHT: only using DHT as fallback, and there are %d working trackers", verified_trackers); debug_log("DHT: only using DHT as fallback, and there are %d working trackers", verified_trackers);
@ -9132,23 +9129,20 @@ bool is_downloading_state(int const st)
&& (num_peers * 100 / m_max_connections > 90 && (num_peers * 100 / m_max_connections > 90
|| num_peers > 20)) || num_peers > 20))
{ {
// we are connected to more than 90% seeds (and we're beyond // we are connected to more than 50% seeds (and we're beyond
// 90% of the max number of connections). That will // 90% of the max number of connections). That will
// limit our ability to upload. We need more downloaders. // limit our ability to upload. We need more downloaders.
// disconnect some seeds so that we don't have more than 50% // disconnect some seeds so that we don't have more than 50%
int const to_disconnect = num_seeds - num_peers / 2; int const to_disconnect = num_seeds - num_peers / 2;
aux::vector<peer_connection*> seeds; aux::vector<peer_connection*> seeds;
seeds.reserve(num_seeds); seeds.reserve(num_seeds);
for (auto const p : m_connections) std::copy_if(m_connections.begin(), m_connections.end(), std::back_inserter(seeds)
{ , [](peer_connection const* p) { return p->is_seed(); });
if (p->is_seed()) seeds.push_back(p);
}
aux::random_shuffle(seeds.begin(), seeds.end()); aux::random_shuffle(seeds.begin(), seeds.end());
TORRENT_ASSERT(to_disconnect <= seeds.end_index()); TORRENT_ASSERT(to_disconnect <= seeds.end_index());
for (int i = 0; i < to_disconnect; ++i) for (auto const& p : span<peer_connection*>(seeds).first(to_disconnect))
seeds[i]->disconnect(errors::upload_upload_connection p->disconnect(errors::upload_upload_connection, operation_t::bittorrent);
, operation_t::bittorrent);
} }
if (num_downloaders == 0) return; if (num_downloaders == 0) return;
@ -9420,9 +9414,7 @@ bool is_downloading_state(int const st)
// then insert them into the interesting_blocks vector // then insert them into the interesting_blocks vector
for (auto const& block : busy_blocks) for (auto const& block : busy_blocks)
{
interesting_blocks.emplace_back(piece, block.index); interesting_blocks.emplace_back(piece, block.index);
}
} }
void pick_time_critical_block(std::vector<peer_connection*>& peers void pick_time_critical_block(std::vector<peer_connection*>& peers

View File

@ -629,14 +629,12 @@ namespace libtorrent {
} }
} }
// TODO: why is this a linked list?
std::list<address> ip_list; std::list<address> ip_list;
for (auto const& endp : m_endpoints) std::transform(m_endpoints.begin(), m_endpoints.end(), std::back_inserter(ip_list)
{ , [](tcp::endpoint const& ep) { return ep.address(); } );
ip_list.push_back(endp.address());
}
cb->tracker_response(tracker_req(), m_target.address(), ip_list cb->tracker_response(tracker_req(), m_target.address(), ip_list, resp);
, resp);
close(); close();
return true; return true;

View File

@ -44,6 +44,10 @@ POSSIBILITY OF SUCH DAMAGE.
#include <cstdint> #include <cstdint>
#include <limits> #include <limits>
#if TORRENT_USE_INVARIANT_CHECKS
#include <numeric> // for accumulate
#endif
// the behavior of the sequence numbers as implemented by uTorrent is not // the behavior of the sequence numbers as implemented by uTorrent is not
// particularly regular. This switch indicates the odd parts. // particularly regular. This switch indicates the odd parts.
#define TORRENT_UT_SEQ 1 #define TORRENT_UT_SEQ 1
@ -302,9 +306,8 @@ struct utp_socket_impl
// TODO: 2 it would be nice if not everything would have to be public here // TODO: 2 it would be nice if not everything would have to be public here
void check_receive_buffers() const;
#if TORRENT_USE_INVARIANT_CHECKS #if TORRENT_USE_INVARIANT_CHECKS
void check_receive_buffers() const;
void check_invariant() const; void check_invariant() const;
#endif #endif
@ -1029,7 +1032,9 @@ std::size_t utp_stream::read_some(bool const clear_buffers)
break; break;
} }
#if TORRENT_USE_INVARIANT_CHECKS
m_impl->check_receive_buffers(); m_impl->check_receive_buffers();
#endif
packet* p = i->get(); packet* p = i->get();
int to_copy = std::min(p->size - p->header_size, aux::numeric_cast<int>(target->len)); int to_copy = std::min(p->size - p->header_size, aux::numeric_cast<int>(target->len));
@ -1045,7 +1050,9 @@ std::size_t utp_stream::read_some(bool const clear_buffers)
p->header_size += std::uint16_t(to_copy); p->header_size += std::uint16_t(to_copy);
if (target->len == 0) target = m_impl->m_read_buffer.erase(target); if (target->len == 0) target = m_impl->m_read_buffer.erase(target);
#if TORRENT_USE_INVARIANT_CHECKS
m_impl->check_receive_buffers(); m_impl->check_receive_buffers();
#endif
TORRENT_ASSERT(m_impl->m_receive_buffer_size >= 0); TORRENT_ASSERT(m_impl->m_receive_buffer_size >= 0);
@ -2391,7 +2398,9 @@ void utp_socket_impl::incoming(std::uint8_t const* buf, int size, packet_ptr p
UTP_LOGV("%8p: incoming: saving packet in receive buffer (%d)\n", static_cast<void*>(this), m_receive_buffer_size); UTP_LOGV("%8p: incoming: saving packet in receive buffer (%d)\n", static_cast<void*>(this), m_receive_buffer_size);
#if TORRENT_USE_INVARIANT_CHECKS
check_receive_buffers(); check_receive_buffers();
#endif
} }
bool utp_socket_impl::cancel_handlers(error_code const& ec, bool shutdown) bool utp_socket_impl::cancel_handlers(error_code const& ec, bool shutdown)
@ -3643,16 +3652,17 @@ void utp_socket_impl::tick(time_point const now)
} }
} }
#if TORRENT_USE_INVARIANT_CHECKS
void utp_socket_impl::check_receive_buffers() const void utp_socket_impl::check_receive_buffers() const
{ {
INVARIANT_CHECK; INVARIANT_CHECK;
int size = 0; int const size = std::accumulate(m_receive_buffer.begin(), m_receive_buffer.end(), 0
for (auto const& p : m_receive_buffer) , [](int const acc, packet_ptr const& p) { return acc + (p ? p->size - p->header_size : 0); } );
size += p ? p->size - p->header_size : 0;
TORRENT_ASSERT(size == m_receive_buffer_size); TORRENT_ASSERT(size == m_receive_buffer_size);
} }
#endif
#if TORRENT_USE_INVARIANT_CHECKS #if TORRENT_USE_INVARIANT_CHECKS
void utp_socket_impl::check_invariant() const void utp_socket_impl::check_invariant() const