Code modernization: subfolders (#6283)
authorLoïc Blot <nerzhul@users.noreply.github.com>
Sat, 19 Aug 2017 20:23:47 +0000 (22:23 +0200)
committerGitHub <noreply@github.com>
Sat, 19 Aug 2017 20:23:47 +0000 (22:23 +0200)
* Code modernization: subfolders

Modernize various code on subfolders client, network, script, threading, unittests, util

* empty function
* default constructor/destructor
* for range-based loops
* use emplace_back instead of push_back
* C++ STL header style
* Make connection.cpp readable in a pointed place + typo

49 files changed:
src/client/tile.cpp
src/client/tile.h
src/network/clientpackethandler.cpp
src/network/connection.cpp
src/network/connection.h
src/network/networkpacket.h
src/network/serverpackethandler.cpp
src/script/lua_api/l_camera.h
src/script/lua_api/l_client.cpp
src/script/lua_api/l_craft.cpp
src/script/lua_api/l_env.cpp
src/script/lua_api/l_http.cpp
src/script/lua_api/l_inventory.cpp
src/script/lua_api/l_inventory.h
src/script/lua_api/l_item.cpp
src/script/lua_api/l_item.h
src/script/lua_api/l_itemstackmeta.h
src/script/lua_api/l_localplayer.h
src/script/lua_api/l_minimap.h
src/script/lua_api/l_nodemeta.cpp
src/script/lua_api/l_nodemeta.h
src/script/lua_api/l_nodetimer.cpp
src/script/lua_api/l_nodetimer.h
src/script/lua_api/l_noise.cpp
src/script/lua_api/l_noise.h
src/script/lua_api/l_object.cpp
src/script/lua_api/l_object.h
src/script/lua_api/l_particles.cpp
src/script/lua_api/l_settings.cpp
src/script/lua_api/l_storage.h
src/script/lua_api/l_util.cpp
src/script/lua_api/l_vmanip.cpp
src/serverenvironment.cpp
src/threading/semaphore.h
src/unittest/test.h
src/unittest/test_noderesolver.cpp
src/unittest/test_schematic.cpp
src/unittest/test_threading.cpp
src/unittest/test_voxelmanipulator.cpp
src/util/auth.cpp
src/util/base64.cpp
src/util/container.h
src/util/numeric.cpp
src/util/pointedthing.h
src/util/serialize.cpp
src/util/serialize.h
src/util/sha1.cpp
src/util/srp.cpp
src/util/thread.h

index 150e621d93969eb8dc284c799854e9e857e7c80f..a2284eed39531747ef8506045ddb9cb412bd819f 100644 (file)
@@ -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);
index 8a8c5bd4788c05f381d7300b8f8ecfb76eea4d7f..d4e25ea6a900bc2e4769dd9fef27ae430c856c82 100644 (file)
@@ -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();
        }
 
        /*!
index d06f8a94dfe9f564b9fe8300e0a77ead3a69c343..1d5a2827723556a2a3a7cf9e83aa2d21b08899af 100644 (file)
@@ -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;
index c93971cac6660ffcc917ca2981ea8a313e5f165d..a74e967841952092de46ee90b12b28435c35474c 100644 (file)
@@ -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");
index bf192870b32d0d5882011d9a1975bec285147861..c64272035cd62bcb7cc9aa089b500f6220ec6beb 100644 (file)
@@ -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()
        {
index 8ba8a62f03b28da29b19f8e833be3e4d85bc1ac3..bc0f26e7d2aa51d24793796df92c9d4ccc04346f 100644 (file)
@@ -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);
index e6b400750f7afba206898a1c1c7b5b1d5e18e498..ecc166d1ece1326dac20139d03ce2fa06317a34f 100644 (file)
@@ -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) {
index a7103c9b050a4903dd061e97bd6996096d1616f6..f3021bc49e0ef509308accacd63266bbd2d0c8b6 100644 (file)
@@ -48,7 +48,7 @@ private:
 
 public:
        LuaCamera(Camera *m);
-       ~LuaCamera() {}
+       ~LuaCamera() = default;
 
        static void create(lua_State *L, Camera *m);
 
index 81dfdb1e98d9699a57a6f8a0e221fa36c6061d2c..6a87b20e98d013b830ab3c31ce4f92e473c94e80 100644 (file)
@@ -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)
 {
index 315391856097fb4b4ea5628cf7b3ac1b51fc62db..7bf1d314b543c2e476008e2d301d1deaf2452d30 100644 (file)
@@ -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);
index 1b1f963898e4c2be521ceeb9f62b3e2a131fe753..94edf201e25ff572eb90f2d73d2c9268912604f4 100644 (file)
@@ -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);
                }
index 8bd39b6ed158f41ce1aa2d70fd3fe4d38b1c5e39..641f4194a54e5a85ccd67409449692625d2e9033 100644 (file)
@@ -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);
                }
        }
index aac5eed8e8d90221841502de2f242fce11238772..b0d43090c3aeb0c73cc1a70eae358c820c0e057f 100644 (file)
@@ -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)
index f12377ecee55ba9172774a57b87ff5898503b148..2b7910ac35fa734b0906d31e0b21e338566f4b62 100644 (file)
@@ -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.
index 0e4fc4ef05509c38ee4fbf005c2847b41e5ba67f..207a04c6cab5254f250968afe5a485095fce4e94 100644 (file)
@@ -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;
index 6aa62808b04569210ca3a775a5c46fff3baddae6..5ff715b2a36fe9bf7ebf10cbdca9c801a542dd3f 100644 (file)
@@ -121,7 +121,7 @@ private:
 
 public:
        LuaItemStack(const ItemStack &item);
-       ~LuaItemStack();
+       ~LuaItemStack() = default;
 
        const ItemStack& getItem() const;
        ItemStack& getItem();
index cfaece794b5ee6ae052f1e65811c205b4a291ce6..241f04c4ce0dff953f622f5e94c8659b93f0e3f3 100644 (file)
@@ -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.
index dcb5c878c06ada4846a0a49bded80318dd54af3f..d30fe1d6431ef313e9ba8c59e8906c99e8d7ce2c 100644 (file)
@@ -70,7 +70,7 @@ private:
 
 public:
        LuaLocalPlayer(LocalPlayer *m);
-       ~LuaLocalPlayer() {}
+       ~LuaLocalPlayer() = default;
 
        static void create(lua_State *L, LocalPlayer *m);
 
index 2d0e6ae9f27d830e627fbe38f05573c470edcfc5..cc859ad0d83b5463e573296f64976755b7547ed5 100644 (file)
@@ -51,7 +51,7 @@ private:
 
 public:
        LuaMinimap(Minimap *m);
-       ~LuaMinimap() {}
+       ~LuaMinimap() = default;
 
        static void create(lua_State *L, Minimap *object);
 
index d1f3140793ddae2926d4102dcb6219f7b86bb775..3d7adf27d8685bd3e3e976520dfe011870ae325d 100644 (file)
@@ -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)
index 683f79932e0cb3928493612bc230ff82c830cdab..b0b4a96237ab4ad64a3d44de306adb5bd6d24386 100644 (file)
@@ -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.
index 17b275c46293516ac453f31cc88b4d11971df5da..55d3aec70c632ed29204b88244201a1e40ee7162 100644 (file)
@@ -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)
index c7cc7624479af8a30ee85f94b9e55c854ef31dda..b894c5c8ca7ad2012eada0c27c427ab6dd096663 100644 (file)
@@ -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.
index e3e76191f841adefef4693f7695a751a80fec007..35d3bbb6eb918ba1d1c8650ac03e1b09b5f449a1 100644 (file)
@@ -36,11 +36,6 @@ LuaPerlinNoise::LuaPerlinNoise(NoiseParams *params) :
 }
 
 
-LuaPerlinNoise::~LuaPerlinNoise()
-{
-}
-
-
 int LuaPerlinNoise::l_get2d(lua_State *L)
 {
        NO_MAP_LOCK_REQUIRED;
index 8af4fbd124f42c6ce5e2240bf1119bae8af800e8..552d67db93b1bdecb137d51495b7f9ac02a135ed 100644 (file)
@@ -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
index 9ddbc3e419ebc6a3e4379aee21582cd3098dba8e..bad5ec8afa5a04a81b7d79c79548d6641b32b402 100644 (file)
@@ -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, &params, &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 &param : 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)
index a2438e4345ffe6ad51d857073acdd30bc242b738..19cc890c7d5d070044d4f2d70926965eca3a3f22 100644 (file)
@@ -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.
index 2f3e9a58df22b645b9d6d784ce5f7a9b2f9751af..8a7de8b4f44ebb17c373681cd04632584a71e9c7 100644 (file)
@@ -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);
        }
index 3dc5c95748782afb020e3d64a47b576c4aa0b4f1..2d6769ea1f912bab7961e189f6b0c6dcd50eccd1 100644 (file)
@@ -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;
index 4e808c393271e12e083ee624c722d293d8b06bc6..f8d102d04409274369873fc5ba9a7e2b5089531c 100644 (file)
@@ -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);
index c68f64a64c809bf53d8300ea9d5642158747f559..dffbc66d16e2d6644c4b076d543112f1752ec3a6 100644 (file)
@@ -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");
        }
index 1e973703c52630aae082ac9bfa7beee48ac45281..a84ecfc0fa265947b664e4a2808b89e517338164 100644 (file)
@@ -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)))
index b552ad72fa28b73d4c604e9e4ee4ee0c7f9d6dae..04015d953bd3418ce6fdef2b4f1cb7fa0750d34b 100644 (file)
@@ -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);
index 76a8f48a6bededb07ba3ee6278f3fd695e320c55..a8847a1005f1214d32a72b122a9ebc652d97e073 100644 (file)
@@ -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);
 };
index c4351a67bfc988901789cad57558f52fac14a641..44b0cd02be5347eb00944fa8de84b5f86863243b 100644 (file)
@@ -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 {                         \
index b009f5d2e5f201b0de66667f4f3fe282ee7df6da..dc2106a54b1db42e464aec4de4120c8d0170c4df 100644 (file)
@@ -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);
index 4801244280f14214f625d64ac49ca9ca5d0c9008..3fea4482908cceeb7041c72f77834a18d79554ab 100644 (file)
@@ -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);
 
index 03d7765394a0f49004562e5815f94c50508163cd..8d4d814fd3ede8f24fd61b680c007a5b7c71981e 100644 (file)
@@ -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);
index 7f8ba3849f0a3d18cc6b174a48a9d2d5eba0555b..6c8ac6757f3b1484bd5d8d581c49723531b4de4a 100644 (file)
@@ -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());
 
index c329e36e6cf50757adf557eaf1066c1fd93fda36..3dd5a9afa605335536ea94da50e614ffae8e1872 100644 (file)
@@ -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
index e14de7de28d291a00f69b2a8af12eba5163a7e5e..c75f98598137ae9511ce73186457e48f7f31869b 100644 (file)
@@ -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;
 }
 
index af85d80e39ba83151cac3766c17f602d4dfd6f08..81f085017247e1fa6adea3454793b54884b3c7e1 100644 (file)
@@ -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()
index e6a9cb75ebddc549631867c17a0b8c2bd5c65e09..a48a72a8a8e8c912d8d2062c2423f2123ee9b75a 100644 (file)
@@ -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
index c13436fcd3aeeb149f62ad55b7943230311e42b0..bd95ef1f3e9f9f84f7db64b6b98842e62a041843 100644 (file)
@@ -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,
index 75843cb1be11ae212d84d90d097421df54041acc..49db9cf853558d915385ccf2cae348fcb2877ac3 100644 (file)
@@ -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();
 }
 
 ////
index 0607ff37a6204b09d5a48a49aa7d88864aa407f8..0a1c96205c414e8e352fa94f53385318f166d87b 100644 (file)
@@ -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>
index c04b6c0c039f8e7e02d482a4cde15569c72f86ac..d61b262afef97d2fc04685c54d567d5a02d409d8 100644 (file)
@@ -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,
index e0ddb9020125de6c6d164a2ef27bc0c7bdbe47ed..aa8dcb4a7e604b4ed38921d263005d409081d06b 100644 (file)
        #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>
 
index fbd04c08ea14c341235c6d9ef1ab6e1a70612f50..52c6c6ababbf2529a58b15c77dd0cf1aedd87538 100644 (file)
@@ -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(); }