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 {
bool is_binary(std::string const& str)
{
for (char const c : str)
{
if (!is_print(c)) return true;
}
return false;
return std::any_of(str.begin(), str.end()
, [](char const c) { return !is_print(c); });
}
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)
{
for (auto const& i : net)
{
if (match_addr_mask(addr, i.interface_address, i.netmask))
return true;
}
return false;
return std::any_of(net.begin(), net.end(), [&addr](ip_interface const& i)
{ return match_addr_mask(addr, i.interface_address, i.netmask); });
}
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::vector<ip_interface> ifs = enum_net_interfaces(ios, ec);
if (ec) return std::string();
if (ec) return {};
for (auto const& iface : ifs)
if (iface.interface_address == addr) return iface.name;
return std::string();
auto const iter = std::find_if(ifs.begin(), ifs.end()
, [&addr](ip_interface const& iface)
{ 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)
{
for (char& c : path)
if (c == '\\') c = '/';
std::replace(path.begin(), path.end(), '\\', '/');
}
#ifdef TORRENT_WINDOWS
void convert_path_to_windows(std::string& path)
{
for (char& c : path)
if (c == '/') c = '\\';
std::replace(path.begin(), path.end(), '/', '\\');
}
#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 =
{{
@ -1229,14 +1229,16 @@ node::protocol_descriptor const& node::map_protocol_to_descriptor(udp protocol)
{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)
return d;
TORRENT_ASSERT_FAIL();
aux::throw_ex<std::out_of_range>("unknown protocol");
}
TORRENT_ASSERT_FAIL();
aux::throw_ex<std::out_of_range>("unknown protocol");
return *iter;
}
} } // namespace libtorrent::dht

View File

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

View File

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

View File

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

View File

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

View File

@ -39,6 +39,7 @@ POSSIBILITY OF SUCH DAMAGE.
#include <cinttypes> // for PRId64 et.al.
#include <functional>
#include <type_traits>
#include <numeric> // for accumulate
#if TORRENT_USE_INVARIANT_CHECKS
#include <unordered_set>
@ -2906,15 +2907,9 @@ namespace aux {
// perform this check.
if (!m_settings.get_bool(settings_pack::incoming_starts_queued_torrents))
{
bool has_active_torrent = false;
for (auto& i : m_torrents)
{
if (!i.second->is_torrent_paused())
{
has_active_torrent = true;
break;
}
}
bool has_active_torrent = std::any_of(m_torrents.begin(), m_torrents.end()
, [](std::pair<sha1_hash, std::shared_ptr<torrent>> const& i)
{ return !i.second->is_torrent_paused(); });
if (!has_active_torrent)
{
#ifndef TORRENT_DISABLE_LOGGING
@ -5068,17 +5063,15 @@ namespace aux {
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)
{
for (auto const& s : m_listen_sockets)
{
if (s->local_endpoint.address() == addr)
{
return s->incoming == duplex::accept_incoming;
}
}
return false;
auto const iter = std::find_if(m_listen_sockets.begin(), m_listen_sockets.end()
, [&addr](std::shared_ptr<listen_socket_t> const& s)
{ return s->local_endpoint.address() == addr; });
return iter == m_listen_sockets.end()
? false
: (*iter)->incoming == duplex::accept_incoming;
}
// 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 (device.empty()) return false;
for (auto const& s : m_outgoing_interfaces)
{
if (s == device) return true;
}
return false;
return std::any_of(m_outgoing_interfaces.begin(), m_outgoing_interfaces.end()
, [&device](std::string const& s) { return s == device; });
}
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
// simply keeping a global counter
int peerlist_size = 0;
for (auto const& i : m_torrents)
{
peerlist_size += i.second->num_known_peers();
}
s.peerlist_size = peerlist_size;
s.peerlist_size = std::accumulate(m_torrents.begin(), m_torrents.end(), 0
, [](int const acc, std::pair<sha1_hash, std::shared_ptr<torrent>> const& t)
{ return acc + t.second->num_known_peers(); });
return s;
}

View File

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

View File

@ -137,8 +137,8 @@ namespace libtorrent {
"abcdefghijklmnopqrstuvwxyz-_.!~*()";
// the random number
for (char& c : dest)
c = printable[random(sizeof(printable) - 2)];
std::generate(dest.begin(), dest.end()
, []{ return printable[random(sizeof(printable) - 2)]; });
}
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 (!settings().get_bool(settings_pack::use_dht_as_fallback)) return true;
int verified_trackers = 0;
for (auto const& tr : m_trackers)
if (tr.verified) ++verified_trackers;
return verified_trackers == 0;
return std::none_of(m_trackers.begin(), m_trackers.end()
, [](announce_entry const& tr) { return bool(tr.verified); });
}
#endif
@ -2566,9 +2563,9 @@ bool is_downloading_state(int const st)
if (settings().get_bool(settings_pack::use_dht_as_fallback))
{
int verified_trackers = 0;
for (auto const& t : m_trackers)
if (t.verified) ++verified_trackers;
int const verified_trackers = static_cast<int>(std::count_if(
m_trackers.begin(), m_trackers.end()
, [](announce_entry const& t) { return t.verified; }));
if (verified_trackers > 0)
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 > 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
// limit our ability to upload. We need more downloaders.
// disconnect some seeds so that we don't have more than 50%
int const to_disconnect = num_seeds - num_peers / 2;
aux::vector<peer_connection*> seeds;
seeds.reserve(num_seeds);
for (auto const p : m_connections)
{
if (p->is_seed()) seeds.push_back(p);
}
std::copy_if(m_connections.begin(), m_connections.end(), std::back_inserter(seeds)
, [](peer_connection const* p) { return p->is_seed(); });
aux::random_shuffle(seeds.begin(), seeds.end());
TORRENT_ASSERT(to_disconnect <= seeds.end_index());
for (int i = 0; i < to_disconnect; ++i)
seeds[i]->disconnect(errors::upload_upload_connection
, operation_t::bittorrent);
for (auto const& p : span<peer_connection*>(seeds).first(to_disconnect))
p->disconnect(errors::upload_upload_connection, operation_t::bittorrent);
}
if (num_downloaders == 0) return;
@ -9420,9 +9414,7 @@ bool is_downloading_state(int const st)
// then insert them into the interesting_blocks vector
for (auto const& block : busy_blocks)
{
interesting_blocks.emplace_back(piece, block.index);
}
}
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;
for (auto const& endp : m_endpoints)
{
ip_list.push_back(endp.address());
}
std::transform(m_endpoints.begin(), m_endpoints.end(), std::back_inserter(ip_list)
, [](tcp::endpoint const& ep) { return ep.address(); } );
cb->tracker_response(tracker_req(), m_target.address(), ip_list
, resp);
cb->tracker_response(tracker_req(), m_target.address(), ip_list, resp);
close();
return true;

View File

@ -44,6 +44,10 @@ POSSIBILITY OF SUCH DAMAGE.
#include <cstdint>
#include <limits>
#if TORRENT_USE_INVARIANT_CHECKS
#include <numeric> // for accumulate
#endif
// the behavior of the sequence numbers as implemented by uTorrent is not
// particularly regular. This switch indicates the odd parts.
#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
void check_receive_buffers() const;
#if TORRENT_USE_INVARIANT_CHECKS
void check_receive_buffers() const;
void check_invariant() const;
#endif
@ -1029,7 +1032,9 @@ std::size_t utp_stream::read_some(bool const clear_buffers)
break;
}
#if TORRENT_USE_INVARIANT_CHECKS
m_impl->check_receive_buffers();
#endif
packet* p = i->get();
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);
if (target->len == 0) target = m_impl->m_read_buffer.erase(target);
#if TORRENT_USE_INVARIANT_CHECKS
m_impl->check_receive_buffers();
#endif
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);
#if TORRENT_USE_INVARIANT_CHECKS
check_receive_buffers();
#endif
}
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
{
INVARIANT_CHECK;
int size = 0;
for (auto const& p : m_receive_buffer)
size += p ? p->size - p->header_size : 0;
int const size = std::accumulate(m_receive_buffer.begin(), m_receive_buffer.end(), 0
, [](int const acc, packet_ptr const& p) { return acc + (p ? p->size - p->header_size : 0); } );
TORRENT_ASSERT(size == m_receive_buffer_size);
}
#endif
#if TORRENT_USE_INVARIANT_CHECKS
void utp_socket_impl::check_invariant() const