diff options
49 files changed, 396 insertions, 516 deletions
diff --git a/src/client/tile.cpp b/src/client/tile.cpp index 150e621d9..a2284eed3 100644 --- a/src/client/tile.cpp +++ b/src/client/tile.cpp @@ -484,43 +484,35 @@ u32 TextureSource::getTextureId(const std::string &name) /* Get texture */ - if (std::this_thread::get_id() == m_main_thread) - { + if (std::this_thread::get_id() == m_main_thread) { return generateTexture(name); } - else - { - infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl; - // We're gonna ask the result to be put into here - static ResultQueue<std::string, u32, u8, u8> result_queue; - // Throw a request in - m_get_texture_queue.add(name, 0, 0, &result_queue); + infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl; - /*infostream<<"Waiting for texture from main thread, name=\"" - <<name<<"\""<<std::endl;*/ + // We're gonna ask the result to be put into here + static ResultQueue<std::string, u32, u8, u8> result_queue; - try - { - while(true) { - // Wait result for a second - GetResult<std::string, u32, u8, u8> - result = result_queue.pop_front(1000); + // Throw a request in + m_get_texture_queue.add(name, 0, 0, &result_queue); - if (result.key == name) { - return result.item; - } + try { + while(true) { + // Wait result for a second + GetResult<std::string, u32, u8, u8> + result = result_queue.pop_front(1000); + + if (result.key == name) { + return result.item; } } - catch(ItemNotFoundException &e) - { - errorstream<<"Waiting for texture " << name << " timed out."<<std::endl; - return 0; - } + } catch(ItemNotFoundException &e) { + errorstream << "Waiting for texture " << name << " timed out." << std::endl; + return 0; } - infostream<<"getTextureId(): Failed"<<std::endl; + infostream << "getTextureId(): Failed" << std::endl; return 0; } @@ -673,7 +665,7 @@ Palette* TextureSource::getPalette(const std::string &name) // Only the main thread may load images sanity_check(std::this_thread::get_id() == m_main_thread); - if (name == "") + if (name.empty()) return NULL; auto it = m_palettes.find(name); diff --git a/src/client/tile.h b/src/client/tile.h index 8a8c5bd47..d4e25ea6a 100644 --- a/src/client/tile.h +++ b/src/client/tile.h @@ -237,6 +237,8 @@ struct TileLayer case TILE_MATERIAL_LIQUID_TRANSPARENT: material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; break; + default: + break; } material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0; if (!(material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL)) { @@ -304,8 +306,8 @@ struct TileLayer struct TileSpec { TileSpec() { - for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) - layers[layer] = TileLayer(); + for (auto &layer : layers) + layer = TileLayer(); } /*! diff --git a/src/network/clientpackethandler.cpp b/src/network/clientpackethandler.cpp index d06f8a94d..1d5a28277 100644 --- a/src/network/clientpackethandler.cpp +++ b/src/network/clientpackethandler.cpp @@ -221,7 +221,7 @@ void Client::handleCommand_AccessDenied(NetworkPacket* pkt) if (denyCode == SERVER_ACCESSDENIED_SHUTDOWN || denyCode == SERVER_ACCESSDENIED_CRASH) { *pkt >> m_access_denied_reason; - if (m_access_denied_reason == "") { + if (m_access_denied_reason.empty()) { m_access_denied_reason = accessDeniedStrings[denyCode]; } u8 reconnect; @@ -237,7 +237,7 @@ void Client::handleCommand_AccessDenied(NetworkPacket* pkt) // Until then (which may be never), this is outside // of the defined protocol. *pkt >> m_access_denied_reason; - if (m_access_denied_reason == "") { + if (m_access_denied_reason.empty()) { m_access_denied_reason = "Unknown"; } } @@ -683,7 +683,7 @@ void Client::handleCommand_AnnounceMedia(NetworkPacket* pkt) Strfnd sf(str); while(!sf.at_end()) { std::string baseurl = trim(sf.next(",")); - if (baseurl != "") + if (!baseurl.empty()) m_media_downloader->addRemoteServer(baseurl); } } @@ -1213,7 +1213,7 @@ void Client::handleCommand_HudSetParam(NetworkPacket* pkt) } else if (param == HUD_PARAM_HOTBAR_IMAGE) { // If value not empty verify image exists in texture source - if (value != "" && !getTextureSource()->isKnownSourceImage(value)) { + if (!value.empty() && !getTextureSource()->isKnownSourceImage(value)) { errorstream << "Server sent wrong Hud hotbar image (sent value: '" << value << "')" << std::endl; return; @@ -1222,7 +1222,7 @@ void Client::handleCommand_HudSetParam(NetworkPacket* pkt) } else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) { // If value not empty verify image exists in texture source - if (value != "" && !getTextureSource()->isKnownSourceImage(value)) { + if (!value.empty() && !getTextureSource()->isKnownSourceImage(value)) { errorstream << "Server sent wrong Hud hotbar selected image (sent value: '" << value << "')" << std::endl; return; diff --git a/src/network/connection.cpp b/src/network/connection.cpp index c93971cac..a74e96784 100644 --- a/src/network/connection.cpp +++ b/src/network/connection.cpp @@ -18,7 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc., */ #include <iomanip> -#include <errno.h> +#include <cerrno> #include "connection.h" #include "serialization.h" #include "log.h" @@ -151,11 +151,9 @@ std::list<SharedBuffer<u8> > makeSplitPacket( } while(end != data.getSize() - 1); - for(std::list<SharedBuffer<u8> >::iterator i = chunks.begin(); - i != chunks.end(); ++i) - { + for (SharedBuffer<u8> &chunk : chunks) { // Write chunk_count - writeU16(&((*i)[3]), chunk_count); + writeU16(&(chunk[3]), chunk_count); } return chunks; @@ -174,15 +172,13 @@ std::list<SharedBuffer<u8> > makeAutoSplitPacket( split_seqnum++; return list; } - else - { - list.push_back(makeOriginalPacket(data)); - } + + list.push_back(makeOriginalPacket(data)); return list; } SharedBuffer<u8> makeReliablePacket( - SharedBuffer<u8> data, + const SharedBuffer<u8> &data, u16 seqnum) { u32 header_size = 3; @@ -206,11 +202,8 @@ void ReliablePacketBuffer::print() MutexAutoLock listlock(m_list_mutex); LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl); unsigned int index = 0; - for(std::list<BufferedPacket>::iterator i = m_list.begin(); - i != m_list.end(); - ++i) - { - u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1])); + for (BufferedPacket &bufferedPacket : m_list) { + u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1])); LOG(dout_con<<index<< ":" << s << std::endl); index++; } @@ -406,11 +399,9 @@ void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected) void ReliablePacketBuffer::incrementTimeouts(float dtime) { MutexAutoLock listlock(m_list_mutex); - for(std::list<BufferedPacket>::iterator i = m_list.begin(); - i != m_list.end(); ++i) - { - i->time += dtime; - i->totaltime += dtime; + for (BufferedPacket &bufferedPacket : m_list) { + bufferedPacket.time += dtime; + bufferedPacket.totaltime += dtime; } } @@ -419,14 +410,12 @@ std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout, { MutexAutoLock listlock(m_list_mutex); std::list<BufferedPacket> timed_outs; - for(std::list<BufferedPacket>::iterator i = m_list.begin(); - i != m_list.end(); ++i) - { - if (i->time >= timeout) { - timed_outs.push_back(*i); + for (BufferedPacket &bufferedPacket : m_list) { + if (bufferedPacket.time >= timeout) { + timed_outs.push_back(bufferedPacket); //this packet will be sent right afterwards reset timeout here - i->time = 0.0; + bufferedPacket.time = 0.0f; if (timed_outs.size() >= max_packets) break; } @@ -441,10 +430,8 @@ std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout, IncomingSplitBuffer::~IncomingSplitBuffer() { MutexAutoLock listlock(m_map_mutex); - for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin(); - i != m_buf.end(); ++i) - { - delete i->second; + for (auto &i : m_buf) { + delete i.second; } } /* @@ -506,15 +493,13 @@ SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable) sp->chunks[chunk_num] = chunkdata; // If not all chunks are received, return empty buffer - if (sp->allReceived() == false) + if (!sp->allReceived()) return SharedBuffer<u8>(); // Calculate total size u32 totalsize = 0; - for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin(); - i != sp->chunks.end(); ++i) - { - totalsize += i->second.getSize(); + for (const auto &chunk : sp->chunks) { + totalsize += chunk.second.getSize(); } SharedBuffer<u8> fulldata(totalsize); @@ -541,25 +526,21 @@ void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout) std::list<u16> remove_queue; { MutexAutoLock listlock(m_map_mutex); - for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin(); - i != m_buf.end(); ++i) - { - IncomingSplitPacket *p = i->second; + for (auto &i : m_buf) { + IncomingSplitPacket *p = i.second; // Reliable ones are not removed by timeout - if (p->reliable == true) + if (p->reliable) continue; p->time += dtime; if (p->time >= timeout) - remove_queue.push_back(i->first); + remove_queue.push_back(i.first); } } - for(std::list<u16>::iterator j = remove_queue.begin(); - j != remove_queue.end(); ++j) - { + for (u16 j : remove_queue) { MutexAutoLock listlock(m_map_mutex); LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl); - delete m_buf[*j]; - m_buf.erase(*j); + delete m_buf[j]; + m_buf.erase(j); } } @@ -929,7 +910,7 @@ void Peer::RTTStatistics(float rtt, const std::string &profiler_id, m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) + jitter * (1/num_samples); - if (profiler_id != "") { + if (!profiler_id.empty()) { g_profiler->graphAdd(profiler_id + "_rtt", rtt); g_profiler->graphAdd(profiler_id + "_jitter", jitter); } @@ -1071,7 +1052,7 @@ bool UDPPeer::processReliableSendCommand( if (c.raw) { - originals.push_back(c.data); + originals.emplace_back(c.data); } else { originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number); @@ -1083,9 +1064,7 @@ bool UDPPeer::processReliableSendCommand( std::queue<BufferedPacket> toadd; volatile u16 initial_sequence_number = 0; - for(std::list<SharedBuffer<u8> >::iterator i = originals.begin(); - i != originals.end(); ++i) - { + for (SharedBuffer<u8> &original : originals) { u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number); /* oops, we don't have enough sequence numbers to send this packet */ @@ -1098,7 +1077,7 @@ bool UDPPeer::processReliableSendCommand( have_initial_sequence_number = true; } - SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum); + SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum); // Add base headers and make a packet BufferedPacket p = con::makePacket(address, reliable, @@ -1110,7 +1089,7 @@ bool UDPPeer::processReliableSendCommand( if (have_sequence_number) { volatile u16 pcount = 0; - while(toadd.size() > 0) { + while (!toadd.empty()) { BufferedPacket p = toadd.front(); toadd.pop(); // LOG(dout_con<<connection->getDesc() @@ -1124,35 +1103,36 @@ bool UDPPeer::processReliableSendCommand( sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF); return true; } - else { - volatile u16 packets_available = toadd.size(); - /* we didn't get a single sequence number no need to fill queue */ - if (!have_initial_sequence_number) - { - return false; - } - while(toadd.size() > 0) { - /* remove packet */ - toadd.pop(); - - bool successfully_put_back_sequence_number - = channels[c.channelnum].putBackSequenceNumber( - (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1))); - FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error"); - } - LOG(dout_con<<m_connection->getDesc() - << " Windowsize exceeded on reliable sending " - << c.data.getSize() << " bytes" - << std::endl << "\t\tinitial_sequence_number: " - << initial_sequence_number - << std::endl << "\t\tgot at most : " - << packets_available << " packets" - << std::endl << "\t\tpackets queued : " - << channels[c.channelnum].outgoing_reliables_sent.size() - << std::endl); + volatile u16 packets_available = toadd.size(); + /* we didn't get a single sequence number no need to fill queue */ + if (!have_initial_sequence_number) { return false; } + + while (!toadd.empty()) { + /* remove packet */ + toadd.pop(); + + bool successfully_put_back_sequence_number + = channels[c.channelnum].putBackSequenceNumber( + (initial_sequence_number+toadd.size() % (SEQNUM_MAX+1))); + + FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error"); + } + + LOG(dout_con<<m_connection->getDesc() + << " Windowsize exceeded on reliable sending " + << c.data.getSize() << " bytes" + << std::endl << "\t\tinitial_sequence_number: " + << initial_sequence_number + << std::endl << "\t\tgot at most : " + << packets_available << " packets" + << std::endl << "\t\tpackets queued : " + << channels[c.channelnum].outgoing_reliables_sent.size() + << std::endl); + + return false; } void UDPPeer::RunCommandQueues( @@ -1161,21 +1141,21 @@ void UDPPeer::RunCommandQueues( unsigned int maxtransfer) { - for (unsigned int i = 0; i < CHANNEL_COUNT; i++) { + for (Channel &channel : channels) { unsigned int commands_processed = 0; - if ((channels[i].queued_commands.size() > 0) && - (channels[i].queued_reliables.size() < maxtransfer) && + if ((!channel.queued_commands.empty()) && + (channel.queued_reliables.size() < maxtransfer) && (commands_processed < maxcommands)) { try { - ConnectionCommand c = channels[i].queued_commands.front(); + ConnectionCommand c = channel.queued_commands.front(); LOG(dout_con << m_connection->getDesc() << " processing queued reliable command " << std::endl); // Packet is processed, remove it from queue if (processReliableSendCommand(c,max_packet_size)) { - channels[i].queued_commands.pop_front(); + channel.queued_commands.pop_front(); } else { LOG(dout_con << m_connection->getDesc() << " Failed to queue packets for peer_id: " << c.peer_id @@ -1291,10 +1271,8 @@ bool ConnectionSendThread::packetsQueued() if (!m_outgoing_queue.empty() && !peerIds.empty()) return true; - for(std::list<u16>::iterator j = peerIds.begin(); - j != peerIds.end(); ++j) - { - PeerHelper peer = m_connection->getPeerNoEx(*j); + for (u16 peerId : peerIds) { + PeerHelper peer = m_connection->getPeerNoEx(peerId); if (!peer) continue; @@ -1302,10 +1280,8 @@ bool ConnectionSendThread::packetsQueued() if (dynamic_cast<UDPPeer*>(&peer) == 0) continue; - for(u16 i=0; i < CHANNEL_COUNT; i++) { - Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i]; - - if (channel->queued_commands.size() > 0) { + for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) { + if (channel.queued_commands.size() > 0) { return true; } } @@ -1320,10 +1296,8 @@ void ConnectionSendThread::runTimeouts(float dtime) std::list<u16> timeouted_peers; std::list<u16> peerIds = m_connection->getPeerIDs(); - for(std::list<u16>::iterator j = peerIds.begin(); - j != peerIds.end(); ++j) - { - PeerHelper peer = m_connection->getPeerNoEx(*j); + for (u16 &peerId : peerIds) { + PeerHelper peer = m_connection->getPeerNoEx(peerId); if (!peer) continue; @@ -1333,7 +1307,7 @@ void ConnectionSendThread::runTimeouts(float dtime) PROFILE(std::stringstream peerIdentifier); PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc() - << ";" << *j << ";RELIABLE]"); + << ";" << peerId << ";RELIABLE]"); PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG)); SharedBuffer<u8> data(2); // data for sending ping, required here because of goto @@ -1356,19 +1330,17 @@ void ConnectionSendThread::runTimeouts(float dtime) float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout(); bool retry_count_exceeded = false; - for(u16 i=0; i<CHANNEL_COUNT; i++) - { + for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) { std::list<BufferedPacket> timed_outs; - Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i]; if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer()) - channel->setWindowSize(g_settings->getU16("workaround_window_size")); + channel.setWindowSize(g_settings->getU16("workaround_window_size")); // Remove timed out incomplete unreliable split packets - channel->incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout); + channel.incoming_splits.removeUnreliableTimedOuts(dtime, m_timeout); // Increment reliable packet times - channel->outgoing_reliables_sent.incrementTimeouts(dtime); + channel.outgoing_reliables_sent.incrementTimeouts(dtime); unsigned int numpeers = m_connection->m_peers.size(); @@ -1376,11 +1348,10 @@ void ConnectionSendThread::runTimeouts(float dtime) return; // Re-send timed out outgoing reliables - timed_outs = channel-> - outgoing_reliables_sent.getTimedOuts(resend_timeout, - (m_max_data_packets_per_iteration/numpeers)); + timed_outs = channel.outgoing_reliables_sent.getTimedOuts(resend_timeout, + (m_max_data_packets_per_iteration/numpeers)); - channel->UpdatePacketLossCounter(timed_outs.size()); + channel.UpdatePacketLossCounter(timed_outs.size()); g_profiler->graphAdd("packets_lost", timed_outs.size()); m_iteration_packets_avaialble -= timed_outs.size(); @@ -1392,7 +1363,7 @@ void ConnectionSendThread::runTimeouts(float dtime) u8 channelnum = readChannel(*(k->data)); u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1])); - channel->UpdateBytesLost(k->data.getSize()); + channel.UpdateBytesLost(k->data.getSize()); k->resend_count++; if (k-> resend_count > MAX_RELIABLE_RETRY) { @@ -1421,7 +1392,7 @@ void ConnectionSendThread::runTimeouts(float dtime) break; /* no need to check other channels if we already did timeout */ } - channel->UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer()); + channel.UpdateTimers(dtime,dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer()); } /* skip to next peer if we did timeout */ @@ -1447,12 +1418,10 @@ void ConnectionSendThread::runTimeouts(float dtime) } // Remove timed out peers - for(std::list<u16>::iterator i = timeouted_peers.begin(); - i != timeouted_peers.end(); ++i) - { - LOG(derr_con<<m_connection->getDesc() - <<"RunTimeouts(): Removing peer "<<(*i)<<std::endl); - m_connection->deletePeer(*i, true); + for (u16 timeouted_peer : timeouted_peers) { + LOG(derr_con << m_connection->getDesc() + << "RunTimeouts(): Removing peer "<< timeouted_peer <<std::endl); + m_connection->deletePeer(timeouted_peer, true); } } @@ -1532,39 +1501,30 @@ bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum, sendAsPacketReliable(p,channel); return true; } - else { - LOG(dout_con<<m_connection->getDesc() - <<" INFO: queueing reliable packet for peer_id: " << peer_id - <<" channel: " << channelnum - <<" seqnum: " << seqnum << std::endl); - channel->queued_reliables.push(p); - return false; - } + + LOG(dout_con<<m_connection->getDesc() + <<" INFO: queueing reliable packet for peer_id: " << peer_id + <<" channel: " << channelnum + <<" seqnum: " << seqnum << std::endl); + channel->queued_reliables.push(p); + return false; } - else - { - Address peer_address; - if (peer->getAddress(MTP_UDP, peer_address)) - { - // Add base headers and make a packet - BufferedPacket p = con::makePacket(peer_address, data, - m_connection->GetProtocolID(), m_connection->GetPeerID(), - channelnum); + Address peer_address; + if (peer->getAddress(MTP_UDP, peer_address)) { + // Add base headers and make a packet + BufferedPacket p = con::makePacket(peer_address, data, + m_connection->GetProtocolID(), m_connection->GetPeerID(), + channelnum); - // Send the packet - rawSend(p); - return true; - } - else { - LOG(dout_con<<m_connection->getDesc() - <<" INFO: dropped unreliable packet for peer_id: " << peer_id - <<" because of (yet) missing udp address" << std::endl); - return false; - } + // Send the packet + rawSend(p); + return true; } - //never reached + LOG(dout_con << m_connection->getDesc() + << " INFO: dropped unreliable packet for peer_id: " << peer_id + << " because of (yet) missing udp address" << std::endl); return false; } @@ -1731,11 +1691,8 @@ void ConnectionSendThread::disconnect() // Send to all std::list<u16> peerids = m_connection->getPeerIDs(); - for (std::list<u16>::iterator i = peerids.begin(); - i != peerids.end(); - ++i) - { - sendAsPacket(*i, 0,data,false); + for (u16 peerid : peerids) { + sendAsPacket(peerid, 0,data,false); } } @@ -1790,10 +1747,7 @@ void ConnectionSendThread::send(u16 peer_id, u8 channelnum, peer->setNextSplitSequenceNumber(channelnum,split_sequence_number); - for(std::list<SharedBuffer<u8> >::iterator i = originals.begin(); - i != originals.end(); ++i) - { - SharedBuffer<u8> original = *i; + for (const SharedBuffer<u8> &original : originals) { sendAsPacket(peer_id, channelnum, original); } } @@ -1811,11 +1765,8 @@ void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data) { std::list<u16> peerids = m_connection->getPeerIDs(); - for (std::list<u16>::iterator i = peerids.begin(); - i != peerids.end(); - ++i) - { - send(*i, channelnum, data); + for (u16 peerid : peerids) { + send(peerid, channelnum, data); } } @@ -1823,11 +1774,8 @@ void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c) { std::list<u16> peerids = m_connection->getPeerIDs(); - for (std::list<u16>::iterator i = peerids.begin(); - i != peerids.end(); - ++i) - { - PeerHelper peer = m_connection->getPeerNoEx(*i); + for (u16 peerid : peerids) { + PeerHelper peer = m_connection->getPeerNoEx(peerid); if (!peer) continue; @@ -1842,85 +1790,84 @@ void ConnectionSendThread::sendPackets(float dtime) std::list<u16> pendingDisconnect; std::map<u16,bool> pending_unreliable; - for(std::list<u16>::iterator - j = peerIds.begin(); - j != peerIds.end(); ++j) - { - PeerHelper peer = m_connection->getPeerNoEx(*j); + for (u16 peerId : peerIds) { + PeerHelper peer = m_connection->getPeerNoEx(peerId); //peer may have been removed if (!peer) { - LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << *j << std::endl); + LOG(dout_con<<m_connection->getDesc()<< " Peer not found: peer_id=" << peerId + << std::endl); continue; } peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size(); - if (dynamic_cast<UDPPeer*>(&peer) == 0) - { + UDPPeer *udpPeer = dynamic_cast<UDPPeer*>(&peer); + + if (!udpPeer) { continue; } - if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect) - { - pendingDisconnect.push_back(*j); + if (udpPeer->m_pending_disconnect) { + pendingDisconnect.push_back(peerId); } PROFILE(std::stringstream peerIdentifier); - PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << *j << ";RELIABLE]"); + PROFILE(peerIdentifier << "sendPackets[" << m_connection->getDesc() << ";" << peerId + << ";RELIABLE]"); PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG)); LOG(dout_con<<m_connection->getDesc() - << " Handle per peer queues: peer_id=" << *j - << " packet quota: " << peer->m_increment_packets_remaining << std::endl); + << " Handle per peer queues: peer_id=" << peerId + << " packet quota: " << peer->m_increment_packets_remaining << std::endl); + // first send queued reliable packets for all peers (if possible) - for (unsigned int i=0; i < CHANNEL_COUNT; i++) - { + for (unsigned int i=0; i < CHANNEL_COUNT; i++) { + Channel &channel = udpPeer->channels[i]; u16 next_to_ack = 0; - dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.getFirstSeqnum(next_to_ack); + + channel.outgoing_reliables_sent.getFirstSeqnum(next_to_ack); u16 next_to_receive = 0; - dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.getFirstSeqnum(next_to_receive); + channel.incoming_reliables.getFirstSeqnum(next_to_receive); LOG(dout_con<<m_connection->getDesc()<< "\t channel: " << i << ", peer quota:" << peer->m_increment_packets_remaining << std::endl << "\t\t\treliables on wire: " - << dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size() + << channel.outgoing_reliables_sent.size() << ", waiting for ack for " << next_to_ack << std::endl << "\t\t\tincoming_reliables: " - << dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size() + << channel.incoming_reliables.size() << ", next reliable packet: " - << dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum() + << channel.readNextIncomingSeqNum() << ", next queued: " << next_to_receive << std::endl << "\t\t\treliables queued : " - << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() + << channel.queued_reliables.size() << std::endl << "\t\t\tqueued commands : " - << dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size() + << channel.queued_commands.size() << std::endl); - while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) && - (dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size() - < dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&& + while ((!channel.queued_reliables.empty()) && + (channel.outgoing_reliables_sent.size() + < channel.getWindowSize())&& (peer->m_increment_packets_remaining > 0)) { - BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.front(); - dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop(); - Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]); + BufferedPacket p = channel.queued_reliables.front(); + channel.queued_reliables.pop(); LOG(dout_con<<m_connection->getDesc() <<" INFO: sending a queued reliable packet " <<" channel: " << i <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1]) << std::endl); - sendAsPacketReliable(p,channel); + sendAsPacketReliable(p, &channel); peer->m_increment_packets_remaining--; } } } - if (m_outgoing_queue.size()) - { + if (!m_outgoing_queue.empty()) { LOG(dout_con<<m_connection->getDesc() << " Handle non reliable queue (" << m_outgoing_queue.size() << " pkts)" << std::endl); @@ -1944,9 +1891,9 @@ void ConnectionSendThread::sendPackets(float dtime) << ", size: " << packet.data.getSize() <<std::endl); continue; } + /* send acks immediately */ - else if (packet.ack) - { + if (packet.ack) { rawSendAsPacket(packet.peer_id, packet.channelnum, packet.data, packet.reliable); peer->m_increment_packets_remaining = @@ -1965,13 +1912,10 @@ void ConnectionSendThread::sendPackets(float dtime) } } - for(std::list<u16>::iterator - k = pendingDisconnect.begin(); - k != pendingDisconnect.end(); ++k) - { - if (!pending_unreliable[*k]) + for (u16 peerId : pendingDisconnect) { + if (!pending_unreliable[peerId]) { - m_connection->deletePeer(*k,false); + m_connection->deletePeer(peerId,false); } } } @@ -2237,21 +2181,16 @@ bool ConnectionReceiveThread::getFromBuffers(u16 &peer_id, SharedBuffer<u8> &dst { std::list<u16> peerids = m_connection->getPeerIDs(); - for(std::list<u16>::iterator j = peerids.begin(); - j != peerids.end(); ++j) - { - PeerHelper peer = m_connection->getPeerNoEx(*j); + for (u16 peerid : peerids) { + PeerHelper peer = m_connection->getPeerNoEx(peerid); if (!peer) continue; if (dynamic_cast<UDPPeer*>(&peer) == 0) continue; - for(u16 i=0; i<CHANNEL_COUNT; i++) - { - Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i]; - - if (checkIncomingBuffers(channel, peer_id, dst)) { + for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) { + if (checkIncomingBuffers(&channel, peer_id, dst)) { return true; } } @@ -2425,8 +2364,7 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel, LOG(dout_con<<m_connection->getDesc() <<"DISCO: Removing peer "<<(peer_id)<<std::endl); - if (m_connection->deletePeer(peer_id, false) == false) - { + if (!m_connection->deletePeer(peer_id, false)) { derr_con<<m_connection->getDesc() <<"DISCO: Peer not found"<<std::endl; } @@ -2662,11 +2600,8 @@ Connection::~Connection() m_receiveThread.wait(); // Delete peers - for(std::map<u16, Peer*>::iterator - j = m_peers.begin(); - j != m_peers.end(); ++j) - { - delete j->second; + for (auto &peer : m_peers) { + delete peer.second; } } @@ -2734,10 +2669,8 @@ u16 Connection::lookupPeer(Address& sender) std::list<Peer*> Connection::getPeers() { std::list<Peer*> list; - for(std::map<u16, Peer*>::iterator j = m_peers.begin(); - j != m_peers.end(); ++j) - { - Peer *peer = j->second; + for (auto &p : m_peers) { + Peer *peer = p.second; list.push_back(peer); } return list; @@ -2904,25 +2837,25 @@ float Connection::getLocalStat(rate_stat_type type) float retval = 0.0; - for (u16 j=0; j<CHANNEL_COUNT; j++) { + for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) { switch(type) { case CUR_DL_RATE: - retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB(); + retval += channel.getCurrentDownloadRateKB(); break; case AVG_DL_RATE: - retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB(); + retval += channel.getAvgDownloadRateKB(); break; case CUR_INC_RATE: - retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB(); + retval += channel.getCurrentIncomingRateKB(); break; case AVG_INC_RATE: - retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB(); + retval += channel.getAvgIncomingRateKB(); break; case AVG_LOSS_RATE: - retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB(); + retval += channel.getAvgLossRateKB(); break; case CUR_LOSS_RATE: - retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB(); + retval += channel.getCurrentLossRateKB(); break; default: FATAL_ERROR("Connection::getLocalStat Invalid stat type"); diff --git a/src/network/connection.h b/src/network/connection.h index bf192870b..c64272035 100644 --- a/src/network/connection.h +++ b/src/network/connection.h @@ -133,16 +133,14 @@ inline bool seqnum_higher(u16 totest, u16 base) { if ((totest - base) > (SEQNUM_MAX/2)) return false; - else - return true; - } - else - { - if ((base - totest) > (SEQNUM_MAX/2)) - return true; - else - return false; + + return true; } + + if ((base - totest) > (SEQNUM_MAX/2)) + return true; + + return false; } inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size) @@ -150,14 +148,12 @@ inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size) u16 window_start = next; u16 window_end = ( next + window_size ) % (SEQNUM_MAX+1); - if (window_start < window_end) - { + if (window_start < window_end) { return ((seqnum >= window_start) && (seqnum < window_end)); } - else - { - return ((seqnum < window_end) || (seqnum >= window_start)); - } + + + return ((seqnum < window_end) || (seqnum >= window_start)); } struct BufferedPacket @@ -166,8 +162,7 @@ struct BufferedPacket data(a_data, a_size) {} BufferedPacket(u32 a_size): - data(a_size), time(0.0), totaltime(0.0), absolute_send_time(-1), - resend_count(0) + data(a_size) {} Buffer<u8> data; // Data of the packet, including headers float time = 0.0f; // Seconds from buffering the packet or re-sending @@ -202,12 +197,13 @@ std::list<SharedBuffer<u8> > makeAutoSplitPacket( // Add the TYPE_RELIABLE header to the data SharedBuffer<u8> makeReliablePacket( - SharedBuffer<u8> data, + const SharedBuffer<u8> &data, u16 seqnum); struct IncomingSplitPacket { - IncomingSplitPacket() {} + IncomingSplitPacket() = default; + // Key is chunk number, value is data without headers std::map<u16, SharedBuffer<u8> > chunks; u32 chunk_count; @@ -315,7 +311,7 @@ typedef std::list<BufferedPacket>::iterator RPBSearchResult; class ReliablePacketBuffer { public: - ReliablePacketBuffer() {}; + ReliablePacketBuffer() = default; bool getFirstSeqnum(u16& result); @@ -410,7 +406,7 @@ struct ConnectionCommand bool reliable = false; bool raw = false; - ConnectionCommand() {} + ConnectionCommand() = default; void serve(Address address_) { @@ -501,8 +497,8 @@ public: IncomingSplitBuffer incoming_splits; - Channel() {}; - ~Channel() {}; + Channel() = default; + ~Channel() = default; void UpdatePacketLossCounter(unsigned int count); void UpdatePacketTooLateCounter(); @@ -590,12 +586,8 @@ class PeerHandler { public: - PeerHandler() - { - } - virtual ~PeerHandler() - { - } + PeerHandler() = default; + virtual ~PeerHandler() = default; /* This is called after the Peer has been inserted into the @@ -612,7 +604,7 @@ public: class PeerHelper { public: - PeerHelper() {}; + PeerHelper() = default;; PeerHelper(Peer* peer); ~PeerHelper(); @@ -744,7 +736,7 @@ class Peer { float max_rtt = 0.0f; float avg_rtt = -1.0f; - rttstats() {}; + rttstats() = default; }; rttstats m_rtt; @@ -769,7 +761,7 @@ public: friend class Connection; UDPPeer(u16 a_id, Address a_address, Connection* connection); - virtual ~UDPPeer() {}; + virtual ~UDPPeer() = default; void PutReliableSendCommand(ConnectionCommand &c, unsigned int max_packet_size); @@ -841,7 +833,7 @@ struct ConnectionEvent bool timeout = false; Address address; - ConnectionEvent() {} + ConnectionEvent() = default; std::string describe() { diff --git a/src/network/networkpacket.h b/src/network/networkpacket.h index 8ba8a62f0..bc0f26e7d 100644 --- a/src/network/networkpacket.h +++ b/src/network/networkpacket.h @@ -30,7 +30,8 @@ class NetworkPacket public: NetworkPacket(u16 command, u32 datasize, u16 peer_id); NetworkPacket(u16 command, u32 datasize); - NetworkPacket() {} + NetworkPacket() = default; + ~NetworkPacket(); void putRawPacket(u8 *data, u32 datasize, u16 peer_id); diff --git a/src/network/serverpackethandler.cpp b/src/network/serverpackethandler.cpp index e6b400750..ecc166d1e 100644 --- a/src/network/serverpackethandler.cpp +++ b/src/network/serverpackethandler.cpp @@ -173,7 +173,7 @@ void Server::handleCommand_Init(NetworkPacket* pkt) return; } - if (string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS) == false) { + if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) { actionstream << "Server: Player with an invalid name " << "tried to connect from " << addr_s << std::endl; DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME); @@ -199,8 +199,7 @@ void Server::handleCommand_Init(NetworkPacket* pkt) << "tried to connect from " << addr_s << " " << "but it was disallowed for the following reason: " << reason << std::endl; - DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING, - reason.c_str()); + DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING, reason); return; } } @@ -468,7 +467,7 @@ void Server::handleCommand_Init_Legacy(NetworkPacket* pkt) return; } - if (string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false) { + if (!string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)) { actionstream << "Server: Player with an invalid name " << "tried to connect from " << addr_s << std::endl; DenyAccess_Legacy(pkt->getPeerId(), L"Name contains unallowed characters"); @@ -489,7 +488,7 @@ void Server::handleCommand_Init_Legacy(NetworkPacket* pkt) << "tried to connect from " << addr_s << " " << "but it was disallowed for the following reason: " << reason << std::endl; - DenyAccess_Legacy(pkt->getPeerId(), utf8_to_wide(reason.c_str())); + DenyAccess_Legacy(pkt->getPeerId(), utf8_to_wide(reason)); return; } } @@ -539,7 +538,7 @@ void Server::handleCommand_Init_Legacy(NetworkPacket* pkt) if (!has_auth) { if (!isSingleplayer() && g_settings->getBool("disallow_empty_password") && - std::string(given_password) == "") { + std::string(given_password).empty()) { actionstream << "Server: " << playername << " supplied empty password" << std::endl; DenyAccess_Legacy(pkt->getPeerId(), L"Empty passwords are " @@ -1637,7 +1636,7 @@ void Server::handleCommand_Interact(NetworkPacket* pkt) RemoteClient *client = getClient(pkt->getPeerId()); v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS)); v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, BS)); - if (item.getDefinition(m_itemdef).node_placement_prediction != "") { + if (!item.getDefinition(m_itemdef).node_placement_prediction.empty()) { client->SetBlockNotSent(blockpos); if (blockpos2 != blockpos) { client->SetBlockNotSent(blockpos2); @@ -1895,10 +1894,10 @@ void Server::handleCommand_SrpBytesA(NetworkPacket* pkt) if (wantSudo) { DenySudoAccess(pkt->getPeerId()); return; - } else { - DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA); - return; } + + DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA); + return; } std::string bytes_A; @@ -1967,10 +1966,10 @@ void Server::handleCommand_SrpBytesA(NetworkPacket* pkt) if (wantSudo) { DenySudoAccess(pkt->getPeerId()); return; - } else { - DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA); - return; } + + DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA); + return; } NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId()); @@ -2004,10 +2003,10 @@ void Server::handleCommand_SrpBytesM(NetworkPacket* pkt) if (wantSudo) { DenySudoAccess(pkt->getPeerId()); return; - } else { - DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA); - return; } + + DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA); + return; } std::string bytes_M; @@ -2035,14 +2034,14 @@ void Server::handleCommand_SrpBytesM(NetworkPacket* pkt) << " (SRP) password for authentication." << std::endl; DenySudoAccess(pkt->getPeerId()); return; - } else { - actionstream << "Server: User " << client->getName() - << " at " << getPeerAddress(pkt->getPeerId()).serializeString() - << " supplied wrong password (auth mechanism: SRP)." - << std::endl; - DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD); - return; } + + actionstream << "Server: User " << client->getName() + << " at " << getPeerAddress(pkt->getPeerId()).serializeString() + << " supplied wrong password (auth mechanism: SRP)." + << std::endl; + DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_PASSWORD); + return; } if (client->create_player_on_auth_success) { diff --git a/src/script/lua_api/l_camera.h b/src/script/lua_api/l_camera.h index a7103c9b0..f3021bc49 100644 --- a/src/script/lua_api/l_camera.h +++ b/src/script/lua_api/l_camera.h @@ -48,7 +48,7 @@ private: public: LuaCamera(Camera *m); - ~LuaCamera() {} + ~LuaCamera() = default; static void create(lua_State *L, Camera *m); diff --git a/src/script/lua_api/l_client.cpp b/src/script/lua_api/l_client.cpp index 81dfdb1e9..6a87b20e9 100644 --- a/src/script/lua_api/l_client.cpp +++ b/src/script/lua_api/l_client.cpp @@ -34,7 +34,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "util/string.h" #include "nodedef.h" -extern MainGameCallback *g_gamecallback; int ModApiClient::l_get_current_modname(lua_State *L) { diff --git a/src/script/lua_api/l_craft.cpp b/src/script/lua_api/l_craft.cpp index 315391856..7bf1d314b 100644 --- a/src/script/lua_api/l_craft.cpp +++ b/src/script/lua_api/l_craft.cpp @@ -57,7 +57,7 @@ bool ModApiCraft::readCraftRecipeShaped(lua_State *L, int index, // key at index -2 and value at index -1 if(!lua_isstring(L, -1)) return false; - recipe.push_back(lua_tostring(L, -1)); + recipe.emplace_back(lua_tostring(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); colcount++; @@ -90,7 +90,7 @@ bool ModApiCraft::readCraftRecipeShapeless(lua_State *L, int index, // key at index -2 and value at index -1 if(!lua_isstring(L, -1)) return false; - recipe.push_back(lua_tostring(L, -1)); + recipe.emplace_back(lua_tostring(L, -1)); // removes value, keeps key for next iteration lua_pop(L, 1); } @@ -122,8 +122,7 @@ bool ModApiCraft::readCraftReplacements(lua_State *L, int index, return false; std::string replace_to = lua_tostring(L, -1); lua_pop(L, 1); - replacements.pairs.push_back( - std::make_pair(replace_from, replace_to)); + replacements.pairs.emplace_back(replace_from, replace_to); // removes value, keeps key for next iteration lua_pop(L, 1); } @@ -148,7 +147,7 @@ int ModApiCraft::l_register_craft(lua_State *L) */ if(type == "shaped"){ std::string output = getstringfield_default(L, table, "output", ""); - if(output == "") + if (output.empty()) throw LuaError("Crafting definition is missing an output"); int width = 0; @@ -179,7 +178,7 @@ int ModApiCraft::l_register_craft(lua_State *L) */ else if(type == "shapeless"){ std::string output = getstringfield_default(L, table, "output", ""); - if(output == "") + if (output.empty()) throw LuaError("Crafting definition (shapeless)" " is missing an output"); @@ -222,12 +221,12 @@ int ModApiCraft::l_register_craft(lua_State *L) */ else if(type == "cooking"){ std::string output = getstringfield_default(L, table, "output", ""); - if(output == "") + if (output.empty()) throw LuaError("Crafting definition (cooking)" " is missing an output"); std::string recipe = getstringfield_default(L, table, "recipe", ""); - if(recipe == "") + if (recipe.empty()) throw LuaError("Crafting definition (cooking)" " is missing a recipe" " (output=\"" + output + "\")"); @@ -252,7 +251,7 @@ int ModApiCraft::l_register_craft(lua_State *L) */ else if(type == "fuel"){ std::string recipe = getstringfield_default(L, table, "recipe", ""); - if(recipe == "") + if (recipe.empty()) throw LuaError("Crafting definition (fuel)" " is missing a recipe"); @@ -294,12 +293,12 @@ int ModApiCraft::l_clear_craft(lua_State *L) std::string output = getstringfield_default(L, table, "output", ""); std::string type = getstringfield_default(L, table, "type", "shaped"); CraftOutput c_output(output, 0); - if (output != "") { + if (!output.empty()) { if (craftdef->clearCraftRecipesByOutput(c_output, getServer(L))) return 0; - else - throw LuaError("No craft recipe known for output" - " (output=\"" + output + "\")"); + + throw LuaError("No craft recipe known for output" + " (output=\"" + output + "\")"); } std::vector<std::string> recipe; int width = 0; @@ -330,7 +329,7 @@ int ModApiCraft::l_clear_craft(lua_State *L) else if (type == "cooking") { method = CRAFT_METHOD_COOKING; std::string rec = getstringfield_default(L, table, "recipe", ""); - if (rec == "") + if (rec.empty()) throw LuaError("Crafting definition (cooking)" " is missing a recipe"); recipe.push_back(rec); @@ -341,7 +340,7 @@ int ModApiCraft::l_clear_craft(lua_State *L) else if (type == "fuel") { method = CRAFT_METHOD_FUEL; std::string rec = getstringfield_default(L, table, "recipe", ""); - if (rec == "") + if (rec.empty()) throw LuaError("Crafting definition (fuel)" " is missing a recipe"); recipe.push_back(rec); diff --git a/src/script/lua_api/l_env.cpp b/src/script/lua_api/l_env.cpp index 1b1f96389..94edf201e 100644 --- a/src/script/lua_api/l_env.cpp +++ b/src/script/lua_api/l_env.cpp @@ -743,9 +743,8 @@ int ModApiEnvMod::l_find_node_near(lua_State *L) for (int d = start_radius; d <= radius; d++) { std::vector<v3s16> list = FacePositionCache::getFacePositions(d); - for (std::vector<v3s16>::iterator i = list.begin(); - i != list.end(); ++i) { - v3s16 p = pos + (*i); + for (v3s16 i : list) { + v3s16 p = pos + i; content_t c = env->getMap().getNodeNoEx(p).getContent(); if (filter.count(c) != 0) { push_v3s16(L, p); @@ -809,10 +808,9 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L) } } lua_newtable(L); - for (std::set<content_t>::const_iterator it = filter.begin(); - it != filter.end(); ++it) { - lua_pushnumber(L, individual_count[*it]); - lua_setfield(L, -2, ndef->get(*it).name.c_str()); + for (content_t it : filter) { + lua_pushnumber(L, individual_count[it]); + lua_setfield(L, -2, ndef->get(it).name.c_str()); } return 2; } @@ -1004,12 +1002,11 @@ int ModApiEnvMod::l_fix_light(lua_State *L) for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) { success = success & map.repairBlockLight(blockpos, &modified_blocks); } - if (modified_blocks.size() > 0) { + if (!modified_blocks.empty()) { MapEditEvent event; event.type = MEET_OTHER; - for (std::map<v3s16, MapBlock *>::iterator it = modified_blocks.begin(); - it != modified_blocks.end(); ++it) - event.modified_blocks.insert(it->first); + for (auto &modified_block : modified_blocks) + event.modified_blocks.insert(modified_block.first); map.dispatchEvent(&event); } @@ -1126,14 +1123,13 @@ int ModApiEnvMod::l_find_path(lua_State *L) std::vector<v3s16> path = get_path(env, pos1, pos2, searchdistance, max_jump, max_drop, algo); - if (path.size() > 0) - { + if (!path.empty()) { lua_newtable(L); int top = lua_gettop(L); unsigned int index = 1; - for (std::vector<v3s16>::iterator i = path.begin(); i != path.end(); ++i) { + for (v3s16 i : path) { lua_pushnumber(L,index); - push_v3s16(L, *i); + push_v3s16(L, i); lua_settable(L, top); index++; } @@ -1167,8 +1163,7 @@ int ModApiEnvMod::l_spawn_tree(lua_State *L) tree_def.leavesnode=ndef->getId(leaves); tree_def.leaves2_chance=0; getstringfield(L, 2, "leaves2", leaves); - if (leaves !="") - { + if (!leaves.empty()) { tree_def.leaves2node=ndef->getId(leaves); getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance); } @@ -1180,8 +1175,7 @@ int ModApiEnvMod::l_spawn_tree(lua_State *L) getboolfield(L, 2, "thin_branches", tree_def.thin_branches); tree_def.fruit_chance=0; getstringfield(L, 2, "fruit", fruit); - if (fruit != "") - { + if (!fruit.empty()) { tree_def.fruitnode=ndef->getId(fruit); getintfield(L, 2, "fruit_chance",tree_def.fruit_chance); } diff --git a/src/script/lua_api/l_http.cpp b/src/script/lua_api/l_http.cpp index 8bd39b6ed..641f4194a 100644 --- a/src/script/lua_api/l_http.cpp +++ b/src/script/lua_api/l_http.cpp @@ -69,7 +69,7 @@ void ModApiHttp::read_http_fetch_request(lua_State *L, HTTPFetchRequest &req) while (lua_next(L, 2) != 0) { const char *header = luaL_checkstring(L, -1); - req.extra_headers.push_back(header); + req.extra_headers.emplace_back(header); lua_pop(L, 1); } } diff --git a/src/script/lua_api/l_inventory.cpp b/src/script/lua_api/l_inventory.cpp index aac5eed8e..b0d43090c 100644 --- a/src/script/lua_api/l_inventory.cpp +++ b/src/script/lua_api/l_inventory.cpp @@ -409,10 +409,6 @@ InvRef::InvRef(const InventoryLocation &loc): { } -InvRef::~InvRef() -{ -} - // Creates an InvRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. void InvRef::create(lua_State *L, const InventoryLocation &loc) diff --git a/src/script/lua_api/l_inventory.h b/src/script/lua_api/l_inventory.h index f12377ece..2b7910ac3 100644 --- a/src/script/lua_api/l_inventory.h +++ b/src/script/lua_api/l_inventory.h @@ -106,7 +106,7 @@ private: public: InvRef(const InventoryLocation &loc); - ~InvRef(); + ~InvRef() = default; // Creates an InvRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. diff --git a/src/script/lua_api/l_item.cpp b/src/script/lua_api/l_item.cpp index 0e4fc4ef0..207a04c6c 100644 --- a/src/script/lua_api/l_item.cpp +++ b/src/script/lua_api/l_item.cpp @@ -67,7 +67,7 @@ int LuaItemStack::l_set_name(lua_State *L) bool status = true; item.name = luaL_checkstring(L, 2); - if (item.name == "" || item.empty()) { + if (item.name.empty() || item.empty()) { item.clear(); status = false; } @@ -231,12 +231,11 @@ int LuaItemStack::l_to_table(lua_State *L) lua_newtable(L); const StringMap &fields = item.metadata.getStrings(); - for (StringMap::const_iterator it = fields.begin(); - it != fields.end(); ++it) { - const std::string &name = it->first; + for (const auto &field : fields) { + const std::string &name = field.first; if (name.empty()) continue; - const std::string &value = it->second; + const std::string &value = field.second; lua_pushlstring(L, name.c_str(), name.size()); lua_pushlstring(L, value.c_str(), value.size()); lua_settable(L, -3); @@ -391,10 +390,6 @@ LuaItemStack::LuaItemStack(const ItemStack &item): { } -LuaItemStack::~LuaItemStack() -{ -} - const ItemStack& LuaItemStack::getItem() const { return m_stack; diff --git a/src/script/lua_api/l_item.h b/src/script/lua_api/l_item.h index 6aa62808b..5ff715b2a 100644 --- a/src/script/lua_api/l_item.h +++ b/src/script/lua_api/l_item.h @@ -121,7 +121,7 @@ private: public: LuaItemStack(const ItemStack &item); - ~LuaItemStack(); + ~LuaItemStack() = default; const ItemStack& getItem() const; ItemStack& getItem(); diff --git a/src/script/lua_api/l_itemstackmeta.h b/src/script/lua_api/l_itemstackmeta.h index cfaece794..241f04c4c 100644 --- a/src/script/lua_api/l_itemstackmeta.h +++ b/src/script/lua_api/l_itemstackmeta.h @@ -46,7 +46,7 @@ private: static int gc_object(lua_State *L); public: ItemStackMetaRef(ItemStack *istack): istack(istack) {} - ~ItemStackMetaRef() {} + ~ItemStackMetaRef() = default; // Creates an ItemStackMetaRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. diff --git a/src/script/lua_api/l_localplayer.h b/src/script/lua_api/l_localplayer.h index dcb5c878c..d30fe1d64 100644 --- a/src/script/lua_api/l_localplayer.h +++ b/src/script/lua_api/l_localplayer.h @@ -70,7 +70,7 @@ private: public: LuaLocalPlayer(LocalPlayer *m); - ~LuaLocalPlayer() {} + ~LuaLocalPlayer() = default; static void create(lua_State *L, LocalPlayer *m); diff --git a/src/script/lua_api/l_minimap.h b/src/script/lua_api/l_minimap.h index 2d0e6ae9f..cc859ad0d 100644 --- a/src/script/lua_api/l_minimap.h +++ b/src/script/lua_api/l_minimap.h @@ -51,7 +51,7 @@ private: public: LuaMinimap(Minimap *m); - ~LuaMinimap() {} + ~LuaMinimap() = default; static void create(lua_State *L, Minimap *object); diff --git a/src/script/lua_api/l_nodemeta.cpp b/src/script/lua_api/l_nodemeta.cpp index d1f314079..3d7adf27d 100644 --- a/src/script/lua_api/l_nodemeta.cpp +++ b/src/script/lua_api/l_nodemeta.cpp @@ -182,10 +182,6 @@ NodeMetaRef::NodeMetaRef(Metadata *meta): { } -NodeMetaRef::~NodeMetaRef() -{ -} - // Creates an NodeMetaRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. void NodeMetaRef::create(lua_State *L, v3s16 p, ServerEnvironment *env) diff --git a/src/script/lua_api/l_nodemeta.h b/src/script/lua_api/l_nodemeta.h index 683f79932..b0b4a9623 100644 --- a/src/script/lua_api/l_nodemeta.h +++ b/src/script/lua_api/l_nodemeta.h @@ -80,7 +80,7 @@ public: NodeMetaRef(v3s16 p, ServerEnvironment *env); NodeMetaRef(Metadata *meta); - ~NodeMetaRef(); + ~NodeMetaRef() = default; // Creates an NodeMetaRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. diff --git a/src/script/lua_api/l_nodetimer.cpp b/src/script/lua_api/l_nodetimer.cpp index 17b275c46..55d3aec70 100644 --- a/src/script/lua_api/l_nodetimer.cpp +++ b/src/script/lua_api/l_nodetimer.cpp @@ -113,10 +113,6 @@ NodeTimerRef::NodeTimerRef(v3s16 p, ServerEnvironment *env): { } -NodeTimerRef::~NodeTimerRef() -{ -} - // Creates an NodeTimerRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. void NodeTimerRef::create(lua_State *L, v3s16 p, ServerEnvironment *env) diff --git a/src/script/lua_api/l_nodetimer.h b/src/script/lua_api/l_nodetimer.h index c7cc76244..b894c5c8c 100644 --- a/src/script/lua_api/l_nodetimer.h +++ b/src/script/lua_api/l_nodetimer.h @@ -51,7 +51,7 @@ private: public: NodeTimerRef(v3s16 p, ServerEnvironment *env); - ~NodeTimerRef(); + ~NodeTimerRef() = default; // Creates an NodeTimerRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. diff --git a/src/script/lua_api/l_noise.cpp b/src/script/lua_api/l_noise.cpp index e3e76191f..35d3bbb6e 100644 --- a/src/script/lua_api/l_noise.cpp +++ b/src/script/lua_api/l_noise.cpp @@ -36,11 +36,6 @@ LuaPerlinNoise::LuaPerlinNoise(NoiseParams *params) : } -LuaPerlinNoise::~LuaPerlinNoise() -{ -} - - int LuaPerlinNoise::l_get2d(lua_State *L) { NO_MAP_LOCK_REQUIRED; diff --git a/src/script/lua_api/l_noise.h b/src/script/lua_api/l_noise.h index 8af4fbd12..552d67db9 100644 --- a/src/script/lua_api/l_noise.h +++ b/src/script/lua_api/l_noise.h @@ -43,7 +43,7 @@ private: public: LuaPerlinNoise(NoiseParams *params); - ~LuaPerlinNoise(); + ~LuaPerlinNoise() = default; // LuaPerlinNoise(seed, octaves, persistence, scale) // Creates an LuaPerlinNoise and leaves it on top of stack diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index 9ddbc3e41..bad5ec8af 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -551,8 +551,8 @@ int ObjectRef::l_get_local_animation(lua_State *L) float frame_speed; player->getLocalAnimations(frames, &frame_speed); - for (int i = 0; i < 4; i++) { - push_v2s32(L, frames[i]); + for (v2s32 frame : frames) { + push_v2s32(L, frame); } lua_pushnumber(L, frame_speed); @@ -611,7 +611,7 @@ int ObjectRef::l_set_bone_position(lua_State *L) ServerActiveObject *co = getobject(ref); if (co == NULL) return 0; // Do it - std::string bone = ""; + std::string bone; if (!lua_isnil(L, 2)) bone = lua_tostring(L, 2); v3f position = v3f(0, 0, 0); @@ -633,7 +633,7 @@ int ObjectRef::l_get_bone_position(lua_State *L) if (co == NULL) return 0; // Do it - std::string bone = ""; + std::string bone; if (!lua_isnil(L, 2)) bone = lua_tostring(L, 2); @@ -661,7 +661,7 @@ int ObjectRef::l_set_attach(lua_State *L) return 0; // Do it int parent_id = 0; - std::string bone = ""; + std::string bone; v3f position = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0); co->getAttachment(&parent_id, &bone, &position, &rotation); @@ -696,7 +696,7 @@ int ObjectRef::l_get_attach(lua_State *L) // Do it int parent_id = 0; - std::string bone = ""; + std::string bone; v3f position = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0); co->getAttachment(&parent_id, &bone, &position, &rotation); @@ -722,7 +722,7 @@ int ObjectRef::l_set_detach(lua_State *L) return 0; int parent_id = 0; - std::string bone = ""; + std::string bone; v3f position; v3f rotation; co->getAttachment(&parent_id, &bone, &position, &rotation); @@ -1223,7 +1223,7 @@ int ObjectRef::l_get_attribute(lua_State *L) std::string attr = luaL_checkstring(L, 2); - std::string value = ""; + std::string value; if (co->getExtendedAttribute(attr, &value)) { lua_pushstring(L, value.c_str()); return 1; @@ -1684,9 +1684,9 @@ int ObjectRef::l_set_sky(lua_State *L) while (lua_next(L, 4) != 0) { // key at index -2 and value at index -1 if (lua_isstring(L, -1)) - params.push_back(lua_tostring(L, -1)); + params.emplace_back(lua_tostring(L, -1)); else - params.push_back(""); + params.emplace_back(""); // removes value, keeps key for next iteration lua_pop(L, 1); } @@ -1720,15 +1720,14 @@ int ObjectRef::l_get_sky(lua_State *L) bool clouds; player->getSky(&bgcolor, &type, ¶ms, &clouds); - type = type == "" ? "regular" : type; + type = type.empty() ? "regular" : type; push_ARGB8(L, bgcolor); lua_pushlstring(L, type.c_str(), type.size()); lua_newtable(L); s16 i = 1; - for (std::vector<std::string>::iterator it = params.begin(); - it != params.end(); ++it) { - lua_pushlstring(L, it->c_str(), it->size()); + for (const std::string ¶m : params) { + lua_pushlstring(L, param.c_str(), param.size()); lua_rawseti(L, -2, i); i++; } @@ -1865,15 +1864,6 @@ ObjectRef::ObjectRef(ServerActiveObject *object): //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl; } -ObjectRef::~ObjectRef() -{ - /*if (m_object) - infostream<<"ObjectRef destructing for id=" - <<m_object->getId()<<std::endl; - else - infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/ -} - // Creates an ObjectRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. void ObjectRef::create(lua_State *L, ServerActiveObject *object) diff --git a/src/script/lua_api/l_object.h b/src/script/lua_api/l_object.h index a2438e434..19cc890c7 100644 --- a/src/script/lua_api/l_object.h +++ b/src/script/lua_api/l_object.h @@ -35,7 +35,7 @@ class ObjectRef : public ModApiBase { public: ObjectRef(ServerActiveObject *object); - ~ObjectRef(); + ~ObjectRef() = default; // Creates an ObjectRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. diff --git a/src/script/lua_api/l_particles.cpp b/src/script/lua_api/l_particles.cpp index 2f3e9a58d..8a7de8b4f 100644 --- a/src/script/lua_api/l_particles.cpp +++ b/src/script/lua_api/l_particles.cpp @@ -53,8 +53,8 @@ int ModApiParticles::l_add_particle(lua_State *L) struct TileAnimationParams animation; animation.type = TAT_NONE; - std::string texture = ""; - std::string playername = ""; + std::string texture; + std::string playername; u8 glow = 0; @@ -158,8 +158,8 @@ int ModApiParticles::l_add_particlespawner(lua_State *L) struct TileAnimationParams animation; animation.type = TAT_NONE; ServerActiveObject *attached = NULL; - std::string texture = ""; - std::string playername = ""; + std::string texture; + std::string playername; u8 glow = 0; if (lua_gettop(L) > 1) //deprecated @@ -262,7 +262,7 @@ int ModApiParticles::l_delete_particlespawner(lua_State *L) // Get parameters u32 id = luaL_checknumber(L, 1); - std::string playername = ""; + std::string playername; if (lua_gettop(L) == 2) { playername = luaL_checkstring(L, 2); } diff --git a/src/script/lua_api/l_settings.cpp b/src/script/lua_api/l_settings.cpp index 3dc5c9574..2d6769ea1 100644 --- a/src/script/lua_api/l_settings.cpp +++ b/src/script/lua_api/l_settings.cpp @@ -198,10 +198,9 @@ int LuaSettings::l_to_table(lua_State* L) std::vector<std::string> keys = o->m_settings->getNames(); lua_newtable(L); - for (unsigned int i=0; i < keys.size(); i++) - { - lua_pushstring(L, o->m_settings->get(keys[i]).c_str()); - lua_setfield(L, -2, keys[i].c_str()); + for (const std::string &key : keys) { + lua_pushstring(L, o->m_settings->get(key).c_str()); + lua_setfield(L, -2, key.c_str()); } return 1; diff --git a/src/script/lua_api/l_storage.h b/src/script/lua_api/l_storage.h index 4e808c393..f8d102d04 100644 --- a/src/script/lua_api/l_storage.h +++ b/src/script/lua_api/l_storage.h @@ -50,7 +50,7 @@ private: public: StorageRef(ModMetadata *object); - ~StorageRef() {} + ~StorageRef() = default; static void Register(lua_State *L); static void create(lua_State *L, ModMetadata *object); diff --git a/src/script/lua_api/l_util.cpp b/src/script/lua_api/l_util.cpp index c68f64a64..dffbc66d1 100644 --- a/src/script/lua_api/l_util.cpp +++ b/src/script/lua_api/l_util.cpp @@ -344,9 +344,9 @@ int ModApiUtil::l_get_dir_list(lua_State *L) int index = 0; lua_newtable(L); - for (size_t i = 0; i < list.size(); i++) { - if (list_all || list_dirs == list[i].dir) { - lua_pushstring(L, list[i].name.c_str()); + for (const fs::DirListNode &dln : list) { + if (list_all || list_dirs == dln.dir) { + lua_pushstring(L, dln.name.c_str()); lua_rawseti(L, -2, ++index); } } @@ -414,7 +414,7 @@ int ModApiUtil::l_get_version(lua_State *L) lua_pushstring(L, g_version_string); lua_setfield(L, table, "string"); - if (strcmp(g_version_string, g_version_hash)) { + if (strcmp(g_version_string, g_version_hash) != 0) { lua_pushstring(L, g_version_hash); lua_setfield(L, table, "hash"); } diff --git a/src/script/lua_api/l_vmanip.cpp b/src/script/lua_api/l_vmanip.cpp index 1e973703c..a84ecfc0f 100644 --- a/src/script/lua_api/l_vmanip.cpp +++ b/src/script/lua_api/l_vmanip.cpp @@ -111,7 +111,7 @@ int LuaVoxelManip::l_write_to_map(lua_State *L) MAP_LOCK_REQUIRED; LuaVoxelManip *o = checkobject(L, 1); - bool update_light = lua_isboolean(L, 2) ? lua_toboolean(L, 2) : true; + bool update_light = !lua_isboolean(L, 2) || lua_toboolean(L, 2); GET_ENV_PTR; ServerMap *map = &(env->getServerMap()); if (o->is_mapgen_vm || !update_light) { @@ -123,9 +123,8 @@ int LuaVoxelManip::l_write_to_map(lua_State *L) MapEditEvent event; event.type = MEET_OTHER; - for (std::map<v3s16, MapBlock *>::iterator it = o->modified_blocks.begin(); - it != o->modified_blocks.end(); ++it) - event.modified_blocks.insert(it->first); + for (const auto &modified_block : o->modified_blocks) + event.modified_blocks.insert(modified_block.first); map->dispatchEvent(&event); @@ -198,7 +197,7 @@ int LuaVoxelManip::l_calc_lighting(lua_State *L) v3s16 fpmax = vm->m_area.MaxEdge; v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : fpmin + yblock; v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : fpmax - yblock; - bool propagate_shadow = lua_isboolean(L, 4) ? lua_toboolean(L, 4) : true; + bool propagate_shadow = !lua_isboolean(L, 4) || lua_toboolean(L, 4); sortBoxVerticies(pmin, pmax); if (!vm->m_area.contains(VoxelArea(pmin, pmax))) diff --git a/src/serverenvironment.cpp b/src/serverenvironment.cpp index b552ad72f..04015d953 100644 --- a/src/serverenvironment.cpp +++ b/src/serverenvironment.cpp @@ -498,7 +498,7 @@ void ServerEnvironment::saveLoadedPlayers() fs::CreateDir(players_path); for (RemotePlayer *player : m_players) { - if (player->checkModified() || (player->getPlayerSAO() && + if (player->checkModified() || (player->getPlayerSAO() && player->getPlayerSAO()->extendedAttributesModified())) { try { m_player_database->savePlayer(player); diff --git a/src/threading/semaphore.h b/src/threading/semaphore.h index 76a8f48a6..a8847a100 100644 --- a/src/threading/semaphore.h +++ b/src/threading/semaphore.h @@ -35,6 +35,8 @@ public: Semaphore(int val = 0); ~Semaphore(); + DISABLE_CLASS_COPY(Semaphore); + void post(unsigned int num = 1); void wait(); bool wait(unsigned int time_ms); @@ -47,6 +49,4 @@ private: #else sem_t semaphore; #endif - - DISABLE_CLASS_COPY(Semaphore); }; diff --git a/src/unittest/test.h b/src/unittest/test.h index c4351a67b..44b0cd02b 100644 --- a/src/unittest/test.h +++ b/src/unittest/test.h @@ -31,7 +31,7 @@ class TestFailedException : public std::exception { }; // Runs a unit test and reports results -#define TEST(fxn, ...) do { \ +#define TEST(fxn, ...) { \ u64 t1 = porting::getTimeMs(); \ try { \ fxn(__VA_ARGS__); \ @@ -47,21 +47,20 @@ class TestFailedException : public std::exception { num_tests_run++; \ u64 tdiff = porting::getTimeMs() - t1; \ rawstream << #fxn << " - " << tdiff << "ms" << std::endl; \ -} while (0) +} // Asserts the specified condition is true, or fails the current unit test -#define UASSERT(x) do { \ +#define UASSERT(x) \ if (!(x)) { \ rawstream << "Test assertion failed: " #x << std::endl \ << " at " << fs::GetFilenameFromPath(__FILE__) \ << ":" << __LINE__ << std::endl; \ throw TestFailedException(); \ - } \ -} while (0) + } // Asserts the specified condition is true, or fails the current unit test // and prints the format specifier fmt -#define UTEST(x, fmt, ...) do { \ +#define UTEST(x, fmt, ...) \ if (!(x)) { \ char utest_buf[1024]; \ snprintf(utest_buf, sizeof(utest_buf), fmt, __VA_ARGS__); \ @@ -69,8 +68,7 @@ class TestFailedException : public std::exception { << " at " << fs::GetFilenameFromPath(__FILE__) \ << ":" << __LINE__ << std::endl; \ throw TestFailedException(); \ - } \ -} while (0) + } // Asserts the comparison specified by CMP is true, or fails the current unit test #define UASSERTCMP(T, CMP, actual, expected) do { \ diff --git a/src/unittest/test_noderesolver.cpp b/src/unittest/test_noderesolver.cpp index b009f5d2e..dc2106a54 100644 --- a/src/unittest/test_noderesolver.cpp +++ b/src/unittest/test_noderesolver.cpp @@ -109,28 +109,28 @@ void TestNodeResolver::testNodeResolving(IWritableNodeDefManager *ndef) Foobar foobar; size_t i; - foobar.m_nodenames.push_back("default:torch"); + foobar.m_nodenames.emplace_back("default:torch"); - foobar.m_nodenames.push_back("default:dirt_with_grass"); - foobar.m_nodenames.push_back("default:water"); - foobar.m_nodenames.push_back("default:abloobloobloo"); - foobar.m_nodenames.push_back("default:stone"); - foobar.m_nodenames.push_back("default:shmegoldorf"); + foobar.m_nodenames.emplace_back("default:dirt_with_grass"); + foobar.m_nodenames.emplace_back("default:water"); + foobar.m_nodenames.emplace_back("default:abloobloobloo"); + foobar.m_nodenames.emplace_back("default:stone"); + foobar.m_nodenames.emplace_back("default:shmegoldorf"); foobar.m_nnlistsizes.push_back(5); - foobar.m_nodenames.push_back("group:liquids"); + foobar.m_nodenames.emplace_back("group:liquids"); foobar.m_nnlistsizes.push_back(1); - foobar.m_nodenames.push_back("default:warf"); - foobar.m_nodenames.push_back("default:stone"); - foobar.m_nodenames.push_back("default:bloop"); + foobar.m_nodenames.emplace_back("default:warf"); + foobar.m_nodenames.emplace_back("default:stone"); + foobar.m_nodenames.emplace_back("default:bloop"); foobar.m_nnlistsizes.push_back(3); foobar.m_nnlistsizes.push_back(0); - foobar.m_nodenames.push_back("default:brick"); - foobar.m_nodenames.push_back("default:desert_stone"); - foobar.m_nodenames.push_back("default:shnitzle"); + foobar.m_nodenames.emplace_back("default:brick"); + foobar.m_nodenames.emplace_back("default:desert_stone"); + foobar.m_nodenames.emplace_back("default:shnitzle"); ndef->pendNodeResolve(&foobar); UASSERT(foobar.m_ndef == ndef); @@ -187,15 +187,15 @@ void TestNodeResolver::testPendingResolveCancellation(IWritableNodeDefManager *n Foobaz foobaz1; foobaz1.test_content1 = 1234; foobaz1.test_content2 = 5678; - foobaz1.m_nodenames.push_back("default:dirt_with_grass"); - foobaz1.m_nodenames.push_back("default:abloobloobloo"); + foobaz1.m_nodenames.emplace_back("default:dirt_with_grass"); + foobaz1.m_nodenames.emplace_back("default:abloobloobloo"); ndef->pendNodeResolve(&foobaz1); Foobaz foobaz2; foobaz2.test_content1 = 1234; foobaz2.test_content2 = 5678; - foobaz2.m_nodenames.push_back("default:dirt_with_grass"); - foobaz2.m_nodenames.push_back("default:abloobloobloo"); + foobaz2.m_nodenames.emplace_back("default:dirt_with_grass"); + foobaz2.m_nodenames.emplace_back("default:abloobloobloo"); ndef->pendNodeResolve(&foobaz2); ndef->cancelNodeResolveCallback(&foobaz1); diff --git a/src/unittest/test_schematic.cpp b/src/unittest/test_schematic.cpp index 480124428..3fea44829 100644 --- a/src/unittest/test_schematic.cpp +++ b/src/unittest/test_schematic.cpp @@ -67,10 +67,10 @@ void TestSchematic::testMtsSerializeDeserialize(INodeDefManager *ndef) std::ios_base::in | std::ios_base::out); std::vector<std::string> names; - names.push_back("foo"); - names.push_back("bar"); - names.push_back("baz"); - names.push_back("qux"); + names.emplace_back("foo"); + names.emplace_back("bar"); + names.emplace_back("baz"); + names.emplace_back("qux"); Schematic schem, schem2; @@ -121,9 +121,9 @@ void TestSchematic::testLuaTableSerialize(INodeDefManager *ndef) schem.slice_probs[y] = MTSCHEM_PROB_ALWAYS; std::vector<std::string> names; - names.push_back("air"); - names.push_back("default:lava_source"); - names.push_back("default:glass"); + names.emplace_back("air"); + names.emplace_back("default:lava_source"); + names.emplace_back("default:glass"); std::ostringstream ss(std::ios_base::binary); diff --git a/src/unittest/test_threading.cpp b/src/unittest/test_threading.cpp index 03d776539..8d4d814fd 100644 --- a/src/unittest/test_threading.cpp +++ b/src/unittest/test_threading.cpp @@ -166,16 +166,16 @@ void TestThreading::testAtomicSemaphoreThread() static const u8 num_threads = 4; AtomicTestThread *threads[num_threads]; - for (u8 i = 0; i < num_threads; ++i) { - threads[i] = new AtomicTestThread(val, trigger); - UASSERT(threads[i]->start()); + for (auto &thread : threads) { + thread = new AtomicTestThread(val, trigger); + UASSERT(thread->start()); } trigger.post(num_threads); - for (u8 i = 0; i < num_threads; ++i) { - threads[i]->wait(); - delete threads[i]; + for (AtomicTestThread *thread : threads) { + thread->wait(); + delete thread; } UASSERT(val == num_threads * 0x10000); diff --git a/src/unittest/test_voxelmanipulator.cpp b/src/unittest/test_voxelmanipulator.cpp index 7f8ba3849..6c8ac6757 100644 --- a/src/unittest/test_voxelmanipulator.cpp +++ b/src/unittest/test_voxelmanipulator.cpp @@ -61,8 +61,8 @@ void TestVoxelManipulator::testVoxelArea() // Correct results std::vector<VoxelArea> results; - results.push_back(VoxelArea(v3s16(-2,-2,-3), v3s16(3,2,-3))); - results.push_back(VoxelArea(v3s16(3,-2,-2), v3s16(3,2,2))); + results.emplace_back(v3s16(-2,-2,-3), v3s16(3,2,-3)); + results.emplace_back(v3s16(3,-2,-2), v3s16(3,2,2)); UASSERT(aa.size() == results.size()); diff --git a/src/util/auth.cpp b/src/util/auth.cpp index c329e36e6..3dd5a9afa 100644 --- a/src/util/auth.cpp +++ b/src/util/auth.cpp @@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "base64.h" #include "sha1.h" #include "srp.h" -#include "string.h" +#include "util/string.h" #include "debug.h" // Get an sha-1 hash of the player's name combined with diff --git a/src/util/base64.cpp b/src/util/base64.cpp index e14de7de2..c75f98598 100644 --- a/src/util/base64.cpp +++ b/src/util/base64.cpp @@ -40,8 +40,9 @@ static inline bool is_base64(unsigned char c) { bool base64_is_valid(std::string const& s) { - for(size_t i=0; i<s.size(); i++) - if(!is_base64(s[i])) return false; + for (char i : s) + if (!is_base64(i)) + return false; return true; } diff --git a/src/util/container.h b/src/util/container.h index af85d80e3..81f085017 100644 --- a/src/util/container.h +++ b/src/util/container.h @@ -79,7 +79,7 @@ template<typename Key, typename Value> class MutexedMap { public: - MutexedMap() {} + MutexedMap() = default; void set(const Key &name, const Value &value) { @@ -128,7 +128,8 @@ public: template<typename Key, typename U, typename Caller, typename CallerData> friend class RequestQueue; - MutexedQueue() {} + MutexedQueue() = default; + bool empty() const { MutexAutoLock lock(m_mutex); @@ -153,9 +154,9 @@ public: T t = m_queue.front(); m_queue.pop_front(); return t; - } else { - return T(); } + + return T(); } T pop_front(u32 wait_time_max_ms) @@ -166,9 +167,9 @@ public: T t = m_queue.front(); m_queue.pop_front(); return t; - } else { - throw ItemNotFoundException("MutexedQueue: queue is empty"); } + + throw ItemNotFoundException("MutexedQueue: queue is empty"); } T pop_frontNoEx() @@ -190,9 +191,9 @@ public: T t = m_queue.back(); m_queue.pop_back(); return t; - } else { - throw ItemNotFoundException("MutexedQueue: queue is empty"); } + + throw ItemNotFoundException("MutexedQueue: queue is empty"); } /* this version of pop_back returns a empty element of T on timeout. @@ -206,9 +207,9 @@ public: T t = m_queue.back(); m_queue.pop_back(); return t; - } else { - return T(); } + + return T(); } T pop_backNoEx() diff --git a/src/util/numeric.cpp b/src/util/numeric.cpp index e6a9cb75e..a48a72a8a 100644 --- a/src/util/numeric.cpp +++ b/src/util/numeric.cpp @@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "../constants.h" // BS, MAP_BLOCKSIZE #include "../noise.h" // PseudoRandom, PcgRandom #include "../threading/mutex_auto_lock.h" -#include <string.h> +#include <cstring> // myrand diff --git a/src/util/pointedthing.h b/src/util/pointedthing.h index c13436fcd..bd95ef1f3 100644 --- a/src/util/pointedthing.h +++ b/src/util/pointedthing.h @@ -81,7 +81,7 @@ struct PointedThing f32 distanceSq = 0; //! Constructor for POINTEDTHING_NOTHING - PointedThing() {}; + PointedThing() = default; //! Constructor for POINTEDTHING_NODE PointedThing(const v3s16 &under, const v3s16 &above, const v3s16 &real_under, const v3f &point, const v3s16 &normal, diff --git a/src/util/serialize.cpp b/src/util/serialize.cpp index 75843cb1b..49db9cf85 100644 --- a/src/util/serialize.cpp +++ b/src/util/serialize.cpp @@ -156,8 +156,8 @@ std::string serializeWideString(const std::wstring &plain) writeU16((u8 *)buf, plain.size()); s.append(buf, 2); - for (u32 i = 0; i < plain.size(); i++) { - writeU16((u8 *)buf, plain[i]); + for (wchar_t i : plain) { + writeU16((u8 *)buf, i); s.append(buf, 2); } return s; @@ -246,8 +246,7 @@ std::string serializeJsonString(const std::string &plain) std::ostringstream os(std::ios::binary); os << "\""; - for (size_t i = 0; i < plain.size(); i++) { - char c = plain[i]; + for (char c : plain) { switch (c) { case '"': os << "\\\""; @@ -308,7 +307,9 @@ std::string deSerializeJsonString(std::istream &is) if (c == '"') { return os.str(); - } else if (c == '\\') { + } + + if (c == '\\') { c2 = is.get(); if (is.eof()) throw SerializationError("JSON string ended prematurely"); @@ -390,17 +391,18 @@ std::string deSerializeJsonStringIfNeeded(std::istream &is) // Found end of word is.unget(); break; - } else { - tmp_os << c; } + + tmp_os << c; } expect_initial_quote = false; } if (is_json) { std::istringstream tmp_is(tmp_os.str(), std::ios::binary); return deSerializeJsonString(tmp_is); - } else - return tmp_os.str(); + } + + return tmp_os.str(); } //// diff --git a/src/util/serialize.h b/src/util/serialize.h index 0607ff37a..0a1c96205 100644 --- a/src/util/serialize.h +++ b/src/util/serialize.h @@ -37,7 +37,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include <endian.h> #endif #endif -#include <string.h> // for memcpy +#include <cstring> // for memcpy #include <iostream> #include <string> #include <vector> diff --git a/src/util/sha1.cpp b/src/util/sha1.cpp index c04b6c0c0..d61b262af 100644 --- a/src/util/sha1.cpp +++ b/src/util/sha1.cpp @@ -24,10 +24,10 @@ SOFTWARE. */ -#include <stdio.h> -#include <string.h> -#include <stdlib.h> -#include <assert.h> +#include <cstdio> +#include <cstring> +#include <cstdlib> +#include <cassert> #include "sha1.h" @@ -96,7 +96,7 @@ void SHA1::process() +(bytes[t*4 + 2] << 8) + bytes[t*4 + 3]; for(; t< 80; t++ ) W[t] = lrot( W[t-3]^W[t-8]^W[t-14]^W[t-16], 1 ); - + /* main loop */ Uint32 temp; for( t = 0; t < 80; t++ ) @@ -154,7 +154,7 @@ void SHA1::addBytes( const char* data, int num ) num -= toCopy; data += toCopy; unprocessedBytes += toCopy; - + // there is a full block if( unprocessedBytes == 64 ) process(); } @@ -168,7 +168,7 @@ unsigned char* SHA1::getDigest() Uint32 totalBitsH = size >> 29; // add 0x80 to the message addBytes( "\x80", 1 ); - + unsigned char footer[64] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, diff --git a/src/util/srp.cpp b/src/util/srp.cpp index e0ddb9020..aa8dcb4a7 100644 --- a/src/util/srp.cpp +++ b/src/util/srp.cpp @@ -31,13 +31,14 @@ #include <windows.h> #include <wincrypt.h> #else - #include <time.h> + #include <ctime> + #endif // clang-format on -#include <stdlib.h> -#include <string.h> -#include <stdio.h> +#include <cstdlib> +#include <cstring> +#include <cstdio> #include <config.h> diff --git a/src/util/thread.h b/src/util/thread.h index fbd04c08e..52c6c6aba 100644 --- a/src/util/thread.h +++ b/src/util/thread.h @@ -78,8 +78,8 @@ public: template<typename Key, typename T, typename Caller, typename CallerData> class GetRequest { public: - GetRequest() {} - ~GetRequest() {} + GetRequest() = default; + ~GetRequest() = default; GetRequest(const Key &a_key): key(a_key) { @@ -189,7 +189,7 @@ class UpdateThread : public Thread { public: UpdateThread(const std::string &name) : Thread(name + "Update") {} - ~UpdateThread() {} + ~UpdateThread() = default; void deferUpdate() { m_update_sem.post(); } |