Code modernization: subfolders (#6283)

* 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
This commit is contained in:
Loïc Blot 2017-08-19 22:23:47 +02:00 committed by GitHub
parent 7528986e44
commit 88b436e6a9
49 changed files with 398 additions and 518 deletions

View File

@ -484,43 +484,35 @@ u32 TextureSource::getTextureId(const std::string &name)
/* /*
Get texture Get texture
*/ */
if (std::this_thread::get_id() == m_main_thread) if (std::this_thread::get_id() == m_main_thread) {
{
return generateTexture(name); 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 infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl;
m_get_texture_queue.add(name, 0, 0, &result_queue);
/*infostream<<"Waiting for texture from main thread, name=\"" // We're gonna ask the result to be put into here
<<name<<"\""<<std::endl;*/ static ResultQueue<std::string, u32, u8, u8> result_queue;
try // Throw a request in
{ m_get_texture_queue.add(name, 0, 0, &result_queue);
while(true) {
// Wait result for a second
GetResult<std::string, u32, u8, u8>
result = result_queue.pop_front(1000);
if (result.key == name) { try {
return result.item; 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) } catch(ItemNotFoundException &e) {
{ errorstream << "Waiting for texture " << name << " timed out." << std::endl;
errorstream<<"Waiting for texture " << name << " timed out."<<std::endl; return 0;
return 0;
}
} }
infostream<<"getTextureId(): Failed"<<std::endl; infostream << "getTextureId(): Failed" << std::endl;
return 0; return 0;
} }
@ -673,7 +665,7 @@ Palette* TextureSource::getPalette(const std::string &name)
// Only the main thread may load images // Only the main thread may load images
sanity_check(std::this_thread::get_id() == m_main_thread); sanity_check(std::this_thread::get_id() == m_main_thread);
if (name == "") if (name.empty())
return NULL; return NULL;
auto it = m_palettes.find(name); auto it = m_palettes.find(name);

View File

@ -237,6 +237,8 @@ struct TileLayer
case TILE_MATERIAL_LIQUID_TRANSPARENT: case TILE_MATERIAL_LIQUID_TRANSPARENT:
material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL; material.MaterialType = video::EMT_TRANSPARENT_ALPHA_CHANNEL;
break; break;
default:
break;
} }
material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0; material.BackfaceCulling = (material_flags & MATERIAL_FLAG_BACKFACE_CULLING) != 0;
if (!(material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL)) { if (!(material_flags & MATERIAL_FLAG_TILEABLE_HORIZONTAL)) {
@ -304,8 +306,8 @@ struct TileLayer
struct TileSpec struct TileSpec
{ {
TileSpec() { TileSpec() {
for (int layer = 0; layer < MAX_TILE_LAYERS; layer++) for (auto &layer : layers)
layers[layer] = TileLayer(); layer = TileLayer();
} }
/*! /*!

View File

@ -221,7 +221,7 @@ void Client::handleCommand_AccessDenied(NetworkPacket* pkt)
if (denyCode == SERVER_ACCESSDENIED_SHUTDOWN || if (denyCode == SERVER_ACCESSDENIED_SHUTDOWN ||
denyCode == SERVER_ACCESSDENIED_CRASH) { denyCode == SERVER_ACCESSDENIED_CRASH) {
*pkt >> m_access_denied_reason; *pkt >> m_access_denied_reason;
if (m_access_denied_reason == "") { if (m_access_denied_reason.empty()) {
m_access_denied_reason = accessDeniedStrings[denyCode]; m_access_denied_reason = accessDeniedStrings[denyCode];
} }
u8 reconnect; u8 reconnect;
@ -237,7 +237,7 @@ void Client::handleCommand_AccessDenied(NetworkPacket* pkt)
// Until then (which may be never), this is outside // Until then (which may be never), this is outside
// of the defined protocol. // of the defined protocol.
*pkt >> m_access_denied_reason; *pkt >> m_access_denied_reason;
if (m_access_denied_reason == "") { if (m_access_denied_reason.empty()) {
m_access_denied_reason = "Unknown"; m_access_denied_reason = "Unknown";
} }
} }
@ -683,7 +683,7 @@ void Client::handleCommand_AnnounceMedia(NetworkPacket* pkt)
Strfnd sf(str); Strfnd sf(str);
while(!sf.at_end()) { while(!sf.at_end()) {
std::string baseurl = trim(sf.next(",")); std::string baseurl = trim(sf.next(","));
if (baseurl != "") if (!baseurl.empty())
m_media_downloader->addRemoteServer(baseurl); m_media_downloader->addRemoteServer(baseurl);
} }
} }
@ -1213,7 +1213,7 @@ void Client::handleCommand_HudSetParam(NetworkPacket* pkt)
} }
else if (param == HUD_PARAM_HOTBAR_IMAGE) { else if (param == HUD_PARAM_HOTBAR_IMAGE) {
// If value not empty verify image exists in texture source // 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: '" errorstream << "Server sent wrong Hud hotbar image (sent value: '"
<< value << "')" << std::endl; << value << "')" << std::endl;
return; return;
@ -1222,7 +1222,7 @@ void Client::handleCommand_HudSetParam(NetworkPacket* pkt)
} }
else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) { else if (param == HUD_PARAM_HOTBAR_SELECTED_IMAGE) {
// If value not empty verify image exists in texture source // 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: '" errorstream << "Server sent wrong Hud hotbar selected image (sent value: '"
<< value << "')" << std::endl; << value << "')" << std::endl;
return; return;

View File

@ -18,7 +18,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
*/ */
#include <iomanip> #include <iomanip>
#include <errno.h> #include <cerrno>
#include "connection.h" #include "connection.h"
#include "serialization.h" #include "serialization.h"
#include "log.h" #include "log.h"
@ -151,11 +151,9 @@ std::list<SharedBuffer<u8> > makeSplitPacket(
} }
while(end != data.getSize() - 1); while(end != data.getSize() - 1);
for(std::list<SharedBuffer<u8> >::iterator i = chunks.begin(); for (SharedBuffer<u8> &chunk : chunks) {
i != chunks.end(); ++i)
{
// Write chunk_count // Write chunk_count
writeU16(&((*i)[3]), chunk_count); writeU16(&(chunk[3]), chunk_count);
} }
return chunks; return chunks;
@ -174,15 +172,13 @@ std::list<SharedBuffer<u8> > makeAutoSplitPacket(
split_seqnum++; split_seqnum++;
return list; return list;
} }
else
{ list.push_back(makeOriginalPacket(data));
list.push_back(makeOriginalPacket(data));
}
return list; return list;
} }
SharedBuffer<u8> makeReliablePacket( SharedBuffer<u8> makeReliablePacket(
SharedBuffer<u8> data, const SharedBuffer<u8> &data,
u16 seqnum) u16 seqnum)
{ {
u32 header_size = 3; u32 header_size = 3;
@ -206,11 +202,8 @@ void ReliablePacketBuffer::print()
MutexAutoLock listlock(m_list_mutex); MutexAutoLock listlock(m_list_mutex);
LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl); LOG(dout_con<<"Dump of ReliablePacketBuffer:" << std::endl);
unsigned int index = 0; unsigned int index = 0;
for(std::list<BufferedPacket>::iterator i = m_list.begin(); for (BufferedPacket &bufferedPacket : m_list) {
i != m_list.end(); u16 s = readU16(&(bufferedPacket.data[BASE_HEADER_SIZE+1]));
++i)
{
u16 s = readU16(&(i->data[BASE_HEADER_SIZE+1]));
LOG(dout_con<<index<< ":" << s << std::endl); LOG(dout_con<<index<< ":" << s << std::endl);
index++; index++;
} }
@ -406,11 +399,9 @@ void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
void ReliablePacketBuffer::incrementTimeouts(float dtime) void ReliablePacketBuffer::incrementTimeouts(float dtime)
{ {
MutexAutoLock listlock(m_list_mutex); MutexAutoLock listlock(m_list_mutex);
for(std::list<BufferedPacket>::iterator i = m_list.begin(); for (BufferedPacket &bufferedPacket : m_list) {
i != m_list.end(); ++i) bufferedPacket.time += dtime;
{ bufferedPacket.totaltime += dtime;
i->time += dtime;
i->totaltime += dtime;
} }
} }
@ -419,14 +410,12 @@ std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
{ {
MutexAutoLock listlock(m_list_mutex); MutexAutoLock listlock(m_list_mutex);
std::list<BufferedPacket> timed_outs; std::list<BufferedPacket> timed_outs;
for(std::list<BufferedPacket>::iterator i = m_list.begin(); for (BufferedPacket &bufferedPacket : m_list) {
i != m_list.end(); ++i) if (bufferedPacket.time >= timeout) {
{ timed_outs.push_back(bufferedPacket);
if (i->time >= timeout) {
timed_outs.push_back(*i);
//this packet will be sent right afterwards reset timeout here //this packet will be sent right afterwards reset timeout here
i->time = 0.0; bufferedPacket.time = 0.0f;
if (timed_outs.size() >= max_packets) if (timed_outs.size() >= max_packets)
break; break;
} }
@ -441,10 +430,8 @@ std::list<BufferedPacket> ReliablePacketBuffer::getTimedOuts(float timeout,
IncomingSplitBuffer::~IncomingSplitBuffer() IncomingSplitBuffer::~IncomingSplitBuffer()
{ {
MutexAutoLock listlock(m_map_mutex); MutexAutoLock listlock(m_map_mutex);
for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin(); for (auto &i : m_buf) {
i != m_buf.end(); ++i) delete i.second;
{
delete i->second;
} }
} }
/* /*
@ -506,15 +493,13 @@ SharedBuffer<u8> IncomingSplitBuffer::insert(BufferedPacket &p, bool reliable)
sp->chunks[chunk_num] = chunkdata; sp->chunks[chunk_num] = chunkdata;
// If not all chunks are received, return empty buffer // If not all chunks are received, return empty buffer
if (sp->allReceived() == false) if (!sp->allReceived())
return SharedBuffer<u8>(); return SharedBuffer<u8>();
// Calculate total size // Calculate total size
u32 totalsize = 0; u32 totalsize = 0;
for(std::map<u16, SharedBuffer<u8> >::iterator i = sp->chunks.begin(); for (const auto &chunk : sp->chunks) {
i != sp->chunks.end(); ++i) totalsize += chunk.second.getSize();
{
totalsize += i->second.getSize();
} }
SharedBuffer<u8> fulldata(totalsize); SharedBuffer<u8> fulldata(totalsize);
@ -541,25 +526,21 @@ void IncomingSplitBuffer::removeUnreliableTimedOuts(float dtime, float timeout)
std::list<u16> remove_queue; std::list<u16> remove_queue;
{ {
MutexAutoLock listlock(m_map_mutex); MutexAutoLock listlock(m_map_mutex);
for(std::map<u16, IncomingSplitPacket*>::iterator i = m_buf.begin(); for (auto &i : m_buf) {
i != m_buf.end(); ++i) IncomingSplitPacket *p = i.second;
{
IncomingSplitPacket *p = i->second;
// Reliable ones are not removed by timeout // Reliable ones are not removed by timeout
if (p->reliable == true) if (p->reliable)
continue; continue;
p->time += dtime; p->time += dtime;
if (p->time >= timeout) 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(); for (u16 j : remove_queue) {
j != remove_queue.end(); ++j)
{
MutexAutoLock listlock(m_map_mutex); MutexAutoLock listlock(m_map_mutex);
LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl); LOG(dout_con<<"NOTE: Removing timed out unreliable split packet"<<std::endl);
delete m_buf[*j]; delete m_buf[j];
m_buf.erase(*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)) + m_rtt.jitter_avg = m_rtt.jitter_avg * (num_samples/(num_samples-1)) +
jitter * (1/num_samples); jitter * (1/num_samples);
if (profiler_id != "") { if (!profiler_id.empty()) {
g_profiler->graphAdd(profiler_id + "_rtt", rtt); g_profiler->graphAdd(profiler_id + "_rtt", rtt);
g_profiler->graphAdd(profiler_id + "_jitter", jitter); g_profiler->graphAdd(profiler_id + "_jitter", jitter);
} }
@ -1071,7 +1052,7 @@ bool UDPPeer::processReliableSendCommand(
if (c.raw) if (c.raw)
{ {
originals.push_back(c.data); originals.emplace_back(c.data);
} }
else { else {
originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number); originals = makeAutoSplitPacket(c.data, chunksize_max,split_sequence_number);
@ -1083,9 +1064,7 @@ bool UDPPeer::processReliableSendCommand(
std::queue<BufferedPacket> toadd; std::queue<BufferedPacket> toadd;
volatile u16 initial_sequence_number = 0; volatile u16 initial_sequence_number = 0;
for(std::list<SharedBuffer<u8> >::iterator i = originals.begin(); for (SharedBuffer<u8> &original : originals) {
i != originals.end(); ++i)
{
u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number); u16 seqnum = channels[c.channelnum].getOutgoingSequenceNumber(have_sequence_number);
/* oops, we don't have enough sequence numbers to send this packet */ /* oops, we don't have enough sequence numbers to send this packet */
@ -1098,7 +1077,7 @@ bool UDPPeer::processReliableSendCommand(
have_initial_sequence_number = true; have_initial_sequence_number = true;
} }
SharedBuffer<u8> reliable = makeReliablePacket(*i, seqnum); SharedBuffer<u8> reliable = makeReliablePacket(original, seqnum);
// Add base headers and make a packet // Add base headers and make a packet
BufferedPacket p = con::makePacket(address, reliable, BufferedPacket p = con::makePacket(address, reliable,
@ -1110,7 +1089,7 @@ bool UDPPeer::processReliableSendCommand(
if (have_sequence_number) { if (have_sequence_number) {
volatile u16 pcount = 0; volatile u16 pcount = 0;
while(toadd.size() > 0) { while (!toadd.empty()) {
BufferedPacket p = toadd.front(); BufferedPacket p = toadd.front();
toadd.pop(); toadd.pop();
// LOG(dout_con<<connection->getDesc() // LOG(dout_con<<connection->getDesc()
@ -1124,35 +1103,36 @@ bool UDPPeer::processReliableSendCommand(
sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF); sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
return true; 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 volatile u16 packets_available = toadd.size();
= channels[c.channelnum].putBackSequenceNumber( /* we didn't get a single sequence number no need to fill queue */
(initial_sequence_number+toadd.size() % (SEQNUM_MAX+1))); if (!have_initial_sequence_number) {
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; 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( void UDPPeer::RunCommandQueues(
@ -1161,21 +1141,21 @@ void UDPPeer::RunCommandQueues(
unsigned int maxtransfer) unsigned int maxtransfer)
{ {
for (unsigned int i = 0; i < CHANNEL_COUNT; i++) { for (Channel &channel : channels) {
unsigned int commands_processed = 0; unsigned int commands_processed = 0;
if ((channels[i].queued_commands.size() > 0) && if ((!channel.queued_commands.empty()) &&
(channels[i].queued_reliables.size() < maxtransfer) && (channel.queued_reliables.size() < maxtransfer) &&
(commands_processed < maxcommands)) { (commands_processed < maxcommands)) {
try { try {
ConnectionCommand c = channels[i].queued_commands.front(); ConnectionCommand c = channel.queued_commands.front();
LOG(dout_con << m_connection->getDesc() LOG(dout_con << m_connection->getDesc()
<< " processing queued reliable command " << std::endl); << " processing queued reliable command " << std::endl);
// Packet is processed, remove it from queue // Packet is processed, remove it from queue
if (processReliableSendCommand(c,max_packet_size)) { if (processReliableSendCommand(c,max_packet_size)) {
channels[i].queued_commands.pop_front(); channel.queued_commands.pop_front();
} else { } else {
LOG(dout_con << m_connection->getDesc() LOG(dout_con << m_connection->getDesc()
<< " Failed to queue packets for peer_id: " << c.peer_id << " Failed to queue packets for peer_id: " << c.peer_id
@ -1291,10 +1271,8 @@ bool ConnectionSendThread::packetsQueued()
if (!m_outgoing_queue.empty() && !peerIds.empty()) if (!m_outgoing_queue.empty() && !peerIds.empty())
return true; return true;
for(std::list<u16>::iterator j = peerIds.begin(); for (u16 peerId : peerIds) {
j != peerIds.end(); ++j) PeerHelper peer = m_connection->getPeerNoEx(peerId);
{
PeerHelper peer = m_connection->getPeerNoEx(*j);
if (!peer) if (!peer)
continue; continue;
@ -1302,10 +1280,8 @@ bool ConnectionSendThread::packetsQueued()
if (dynamic_cast<UDPPeer*>(&peer) == 0) if (dynamic_cast<UDPPeer*>(&peer) == 0)
continue; continue;
for(u16 i=0; i < CHANNEL_COUNT; i++) { for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i]; if (channel.queued_commands.size() > 0) {
if (channel->queued_commands.size() > 0) {
return true; return true;
} }
} }
@ -1320,10 +1296,8 @@ void ConnectionSendThread::runTimeouts(float dtime)
std::list<u16> timeouted_peers; std::list<u16> timeouted_peers;
std::list<u16> peerIds = m_connection->getPeerIDs(); std::list<u16> peerIds = m_connection->getPeerIDs();
for(std::list<u16>::iterator j = peerIds.begin(); for (u16 &peerId : peerIds) {
j != peerIds.end(); ++j) PeerHelper peer = m_connection->getPeerNoEx(peerId);
{
PeerHelper peer = m_connection->getPeerNoEx(*j);
if (!peer) if (!peer)
continue; continue;
@ -1333,7 +1307,7 @@ void ConnectionSendThread::runTimeouts(float dtime)
PROFILE(std::stringstream peerIdentifier); PROFILE(std::stringstream peerIdentifier);
PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc() PROFILE(peerIdentifier << "runTimeouts[" << m_connection->getDesc()
<< ";" << *j << ";RELIABLE]"); << ";" << peerId << ";RELIABLE]");
PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG)); PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
SharedBuffer<u8> data(2); // data for sending ping, required here because of goto 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(); float resend_timeout = dynamic_cast<UDPPeer*>(&peer)->getResendTimeout();
bool retry_count_exceeded = false; 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; std::list<BufferedPacket> timed_outs;
Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
if (dynamic_cast<UDPPeer*>(&peer)->getLegacyPeer()) 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 // 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 // Increment reliable packet times
channel->outgoing_reliables_sent.incrementTimeouts(dtime); channel.outgoing_reliables_sent.incrementTimeouts(dtime);
unsigned int numpeers = m_connection->m_peers.size(); unsigned int numpeers = m_connection->m_peers.size();
@ -1376,11 +1348,10 @@ void ConnectionSendThread::runTimeouts(float dtime)
return; return;
// Re-send timed out outgoing reliables // Re-send timed out outgoing reliables
timed_outs = channel-> timed_outs = channel.outgoing_reliables_sent.getTimedOuts(resend_timeout,
outgoing_reliables_sent.getTimedOuts(resend_timeout, (m_max_data_packets_per_iteration/numpeers));
(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()); g_profiler->graphAdd("packets_lost", timed_outs.size());
m_iteration_packets_avaialble -= timed_outs.size(); m_iteration_packets_avaialble -= timed_outs.size();
@ -1392,7 +1363,7 @@ void ConnectionSendThread::runTimeouts(float dtime)
u8 channelnum = readChannel(*(k->data)); u8 channelnum = readChannel(*(k->data));
u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1])); u16 seqnum = readU16(&(k->data[BASE_HEADER_SIZE+1]));
channel->UpdateBytesLost(k->data.getSize()); channel.UpdateBytesLost(k->data.getSize());
k->resend_count++; k->resend_count++;
if (k-> resend_count > MAX_RELIABLE_RETRY) { 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 */ 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 */ /* skip to next peer if we did timeout */
@ -1447,12 +1418,10 @@ void ConnectionSendThread::runTimeouts(float dtime)
} }
// Remove timed out peers // Remove timed out peers
for(std::list<u16>::iterator i = timeouted_peers.begin(); for (u16 timeouted_peer : timeouted_peers) {
i != timeouted_peers.end(); ++i) LOG(derr_con << m_connection->getDesc()
{ << "RunTimeouts(): Removing peer "<< timeouted_peer <<std::endl);
LOG(derr_con<<m_connection->getDesc() m_connection->deletePeer(timeouted_peer, true);
<<"RunTimeouts(): Removing peer "<<(*i)<<std::endl);
m_connection->deletePeer(*i, true);
} }
} }
@ -1532,39 +1501,30 @@ bool ConnectionSendThread::rawSendAsPacket(u16 peer_id, u8 channelnum,
sendAsPacketReliable(p,channel); sendAsPacketReliable(p,channel);
return true; 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;
}
}
else
{
Address peer_address;
if (peer->getAddress(MTP_UDP, peer_address)) LOG(dout_con<<m_connection->getDesc()
{ <<" INFO: queueing reliable packet for peer_id: " << peer_id
// Add base headers and make a packet <<" channel: " << channelnum
BufferedPacket p = con::makePacket(peer_address, data, <<" seqnum: " << seqnum << std::endl);
m_connection->GetProtocolID(), m_connection->GetPeerID(), channel->queued_reliables.push(p);
channelnum); return false;
// 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;
}
} }
//never reached 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;
}
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; return false;
} }
@ -1731,11 +1691,8 @@ void ConnectionSendThread::disconnect()
// Send to all // Send to all
std::list<u16> peerids = m_connection->getPeerIDs(); std::list<u16> peerids = m_connection->getPeerIDs();
for (std::list<u16>::iterator i = peerids.begin(); for (u16 peerid : peerids) {
i != peerids.end(); sendAsPacket(peerid, 0,data,false);
++i)
{
sendAsPacket(*i, 0,data,false);
} }
} }
@ -1790,10 +1747,7 @@ void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
peer->setNextSplitSequenceNumber(channelnum,split_sequence_number); peer->setNextSplitSequenceNumber(channelnum,split_sequence_number);
for(std::list<SharedBuffer<u8> >::iterator i = originals.begin(); for (const SharedBuffer<u8> &original : originals) {
i != originals.end(); ++i)
{
SharedBuffer<u8> original = *i;
sendAsPacket(peer_id, channelnum, original); sendAsPacket(peer_id, channelnum, original);
} }
} }
@ -1811,11 +1765,8 @@ void ConnectionSendThread::sendToAll(u8 channelnum, SharedBuffer<u8> data)
{ {
std::list<u16> peerids = m_connection->getPeerIDs(); std::list<u16> peerids = m_connection->getPeerIDs();
for (std::list<u16>::iterator i = peerids.begin(); for (u16 peerid : peerids) {
i != peerids.end(); send(peerid, channelnum, data);
++i)
{
send(*i, channelnum, data);
} }
} }
@ -1823,11 +1774,8 @@ void ConnectionSendThread::sendToAllReliable(ConnectionCommand &c)
{ {
std::list<u16> peerids = m_connection->getPeerIDs(); std::list<u16> peerids = m_connection->getPeerIDs();
for (std::list<u16>::iterator i = peerids.begin(); for (u16 peerid : peerids) {
i != peerids.end(); PeerHelper peer = m_connection->getPeerNoEx(peerid);
++i)
{
PeerHelper peer = m_connection->getPeerNoEx(*i);
if (!peer) if (!peer)
continue; continue;
@ -1842,85 +1790,84 @@ void ConnectionSendThread::sendPackets(float dtime)
std::list<u16> pendingDisconnect; std::list<u16> pendingDisconnect;
std::map<u16,bool> pending_unreliable; std::map<u16,bool> pending_unreliable;
for(std::list<u16>::iterator for (u16 peerId : peerIds) {
j = peerIds.begin(); PeerHelper peer = m_connection->getPeerNoEx(peerId);
j != peerIds.end(); ++j)
{
PeerHelper peer = m_connection->getPeerNoEx(*j);
//peer may have been removed //peer may have been removed
if (!peer) { 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; continue;
} }
peer->m_increment_packets_remaining = m_iteration_packets_avaialble/m_connection->m_peers.size(); 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; continue;
} }
if (dynamic_cast<UDPPeer*>(&peer)->m_pending_disconnect) if (udpPeer->m_pending_disconnect) {
{ pendingDisconnect.push_back(peerId);
pendingDisconnect.push_back(*j);
} }
PROFILE(std::stringstream peerIdentifier); 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)); PROFILE(ScopeProfiler peerprofiler(g_profiler, peerIdentifier.str(), SPT_AVG));
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
<< " Handle per peer queues: peer_id=" << *j << " Handle per peer queues: peer_id=" << peerId
<< " packet quota: " << peer->m_increment_packets_remaining << std::endl); << " packet quota: " << peer->m_increment_packets_remaining << std::endl);
// first send queued reliable packets for all peers (if possible) // 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; 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; 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: " LOG(dout_con<<m_connection->getDesc()<< "\t channel: "
<< i << ", peer quota:" << i << ", peer quota:"
<< peer->m_increment_packets_remaining << peer->m_increment_packets_remaining
<< std::endl << std::endl
<< "\t\t\treliables on wire: " << "\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 << ", waiting for ack for " << next_to_ack
<< std::endl << std::endl
<< "\t\t\tincoming_reliables: " << "\t\t\tincoming_reliables: "
<< dynamic_cast<UDPPeer*>(&peer)->channels[i].incoming_reliables.size() << channel.incoming_reliables.size()
<< ", next reliable packet: " << ", next reliable packet: "
<< dynamic_cast<UDPPeer*>(&peer)->channels[i].readNextIncomingSeqNum() << channel.readNextIncomingSeqNum()
<< ", next queued: " << next_to_receive << ", next queued: " << next_to_receive
<< std::endl << std::endl
<< "\t\t\treliables queued : " << "\t\t\treliables queued : "
<< dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() << channel.queued_reliables.size()
<< std::endl << std::endl
<< "\t\t\tqueued commands : " << "\t\t\tqueued commands : "
<< dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_commands.size() << channel.queued_commands.size()
<< std::endl); << std::endl);
while ((dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.size() > 0) && while ((!channel.queued_reliables.empty()) &&
(dynamic_cast<UDPPeer*>(&peer)->channels[i].outgoing_reliables_sent.size() (channel.outgoing_reliables_sent.size()
< dynamic_cast<UDPPeer*>(&peer)->channels[i].getWindowSize())&& < channel.getWindowSize())&&
(peer->m_increment_packets_remaining > 0)) (peer->m_increment_packets_remaining > 0))
{ {
BufferedPacket p = dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.front(); BufferedPacket p = channel.queued_reliables.front();
dynamic_cast<UDPPeer*>(&peer)->channels[i].queued_reliables.pop(); channel.queued_reliables.pop();
Channel* channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[i]);
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
<<" INFO: sending a queued reliable packet " <<" INFO: sending a queued reliable packet "
<<" channel: " << i <<" channel: " << i
<<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1]) <<", seqnum: " << readU16(&p.data[BASE_HEADER_SIZE+1])
<< std::endl); << std::endl);
sendAsPacketReliable(p,channel); sendAsPacketReliable(p, &channel);
peer->m_increment_packets_remaining--; peer->m_increment_packets_remaining--;
} }
} }
} }
if (m_outgoing_queue.size()) if (!m_outgoing_queue.empty()) {
{
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
<< " Handle non reliable queue (" << " Handle non reliable queue ("
<< m_outgoing_queue.size() << " pkts)" << std::endl); << m_outgoing_queue.size() << " pkts)" << std::endl);
@ -1944,9 +1891,9 @@ void ConnectionSendThread::sendPackets(float dtime)
<< ", size: " << packet.data.getSize() <<std::endl); << ", size: " << packet.data.getSize() <<std::endl);
continue; continue;
} }
/* send acks immediately */ /* send acks immediately */
else if (packet.ack) if (packet.ack) {
{
rawSendAsPacket(packet.peer_id, packet.channelnum, rawSendAsPacket(packet.peer_id, packet.channelnum,
packet.data, packet.reliable); packet.data, packet.reliable);
peer->m_increment_packets_remaining = peer->m_increment_packets_remaining =
@ -1965,13 +1912,10 @@ void ConnectionSendThread::sendPackets(float dtime)
} }
} }
for(std::list<u16>::iterator for (u16 peerId : pendingDisconnect) {
k = pendingDisconnect.begin(); if (!pending_unreliable[peerId])
k != pendingDisconnect.end(); ++k)
{
if (!pending_unreliable[*k])
{ {
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(); std::list<u16> peerids = m_connection->getPeerIDs();
for(std::list<u16>::iterator j = peerids.begin(); for (u16 peerid : peerids) {
j != peerids.end(); ++j) PeerHelper peer = m_connection->getPeerNoEx(peerid);
{
PeerHelper peer = m_connection->getPeerNoEx(*j);
if (!peer) if (!peer)
continue; continue;
if (dynamic_cast<UDPPeer*>(&peer) == 0) if (dynamic_cast<UDPPeer*>(&peer) == 0)
continue; continue;
for(u16 i=0; i<CHANNEL_COUNT; i++) for (Channel &channel : (dynamic_cast<UDPPeer *>(&peer))->channels) {
{ if (checkIncomingBuffers(&channel, peer_id, dst)) {
Channel *channel = &(dynamic_cast<UDPPeer*>(&peer))->channels[i];
if (checkIncomingBuffers(channel, peer_id, dst)) {
return true; return true;
} }
} }
@ -2425,8 +2364,7 @@ SharedBuffer<u8> ConnectionReceiveThread::processPacket(Channel *channel,
LOG(dout_con<<m_connection->getDesc() LOG(dout_con<<m_connection->getDesc()
<<"DISCO: Removing peer "<<(peer_id)<<std::endl); <<"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() derr_con<<m_connection->getDesc()
<<"DISCO: Peer not found"<<std::endl; <<"DISCO: Peer not found"<<std::endl;
} }
@ -2662,11 +2600,8 @@ Connection::~Connection()
m_receiveThread.wait(); m_receiveThread.wait();
// Delete peers // Delete peers
for(std::map<u16, Peer*>::iterator for (auto &peer : m_peers) {
j = m_peers.begin(); delete peer.second;
j != m_peers.end(); ++j)
{
delete j->second;
} }
} }
@ -2734,10 +2669,8 @@ u16 Connection::lookupPeer(Address& sender)
std::list<Peer*> Connection::getPeers() std::list<Peer*> Connection::getPeers()
{ {
std::list<Peer*> list; std::list<Peer*> list;
for(std::map<u16, Peer*>::iterator j = m_peers.begin(); for (auto &p : m_peers) {
j != m_peers.end(); ++j) Peer *peer = p.second;
{
Peer *peer = j->second;
list.push_back(peer); list.push_back(peer);
} }
return list; return list;
@ -2904,25 +2837,25 @@ float Connection::getLocalStat(rate_stat_type type)
float retval = 0.0; float retval = 0.0;
for (u16 j=0; j<CHANNEL_COUNT; j++) { for (Channel &channel : dynamic_cast<UDPPeer *>(&peer)->channels) {
switch(type) { switch(type) {
case CUR_DL_RATE: case CUR_DL_RATE:
retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentDownloadRateKB(); retval += channel.getCurrentDownloadRateKB();
break; break;
case AVG_DL_RATE: case AVG_DL_RATE:
retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgDownloadRateKB(); retval += channel.getAvgDownloadRateKB();
break; break;
case CUR_INC_RATE: case CUR_INC_RATE:
retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentIncomingRateKB(); retval += channel.getCurrentIncomingRateKB();
break; break;
case AVG_INC_RATE: case AVG_INC_RATE:
retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgIncomingRateKB(); retval += channel.getAvgIncomingRateKB();
break; break;
case AVG_LOSS_RATE: case AVG_LOSS_RATE:
retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getAvgLossRateKB(); retval += channel.getAvgLossRateKB();
break; break;
case CUR_LOSS_RATE: case CUR_LOSS_RATE:
retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB(); retval += channel.getCurrentLossRateKB();
break; break;
default: default:
FATAL_ERROR("Connection::getLocalStat Invalid stat type"); FATAL_ERROR("Connection::getLocalStat Invalid stat type");

View File

@ -133,16 +133,14 @@ inline bool seqnum_higher(u16 totest, u16 base)
{ {
if ((totest - base) > (SEQNUM_MAX/2)) if ((totest - base) > (SEQNUM_MAX/2))
return false; return false;
else
return true; return true;
}
else
{
if ((base - totest) > (SEQNUM_MAX/2))
return true;
else
return false;
} }
if ((base - totest) > (SEQNUM_MAX/2))
return true;
return false;
} }
inline bool seqnum_in_window(u16 seqnum, u16 next,u16 window_size) 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_start = next;
u16 window_end = ( next + window_size ) % (SEQNUM_MAX+1); 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)); return ((seqnum >= window_start) && (seqnum < window_end));
} }
else
{
return ((seqnum < window_end) || (seqnum >= window_start)); return ((seqnum < window_end) || (seqnum >= window_start));
}
} }
struct BufferedPacket struct BufferedPacket
@ -166,8 +162,7 @@ struct BufferedPacket
data(a_data, a_size) data(a_data, a_size)
{} {}
BufferedPacket(u32 a_size): BufferedPacket(u32 a_size):
data(a_size), time(0.0), totaltime(0.0), absolute_send_time(-1), data(a_size)
resend_count(0)
{} {}
Buffer<u8> data; // Data of the packet, including headers Buffer<u8> data; // Data of the packet, including headers
float time = 0.0f; // Seconds from buffering the packet or re-sending 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 // Add the TYPE_RELIABLE header to the data
SharedBuffer<u8> makeReliablePacket( SharedBuffer<u8> makeReliablePacket(
SharedBuffer<u8> data, const SharedBuffer<u8> &data,
u16 seqnum); u16 seqnum);
struct IncomingSplitPacket struct IncomingSplitPacket
{ {
IncomingSplitPacket() {} IncomingSplitPacket() = default;
// Key is chunk number, value is data without headers // Key is chunk number, value is data without headers
std::map<u16, SharedBuffer<u8> > chunks; std::map<u16, SharedBuffer<u8> > chunks;
u32 chunk_count; u32 chunk_count;
@ -315,7 +311,7 @@ typedef std::list<BufferedPacket>::iterator RPBSearchResult;
class ReliablePacketBuffer class ReliablePacketBuffer
{ {
public: public:
ReliablePacketBuffer() {}; ReliablePacketBuffer() = default;
bool getFirstSeqnum(u16& result); bool getFirstSeqnum(u16& result);
@ -410,7 +406,7 @@ struct ConnectionCommand
bool reliable = false; bool reliable = false;
bool raw = false; bool raw = false;
ConnectionCommand() {} ConnectionCommand() = default;
void serve(Address address_) void serve(Address address_)
{ {
@ -501,8 +497,8 @@ public:
IncomingSplitBuffer incoming_splits; IncomingSplitBuffer incoming_splits;
Channel() {}; Channel() = default;
~Channel() {}; ~Channel() = default;
void UpdatePacketLossCounter(unsigned int count); void UpdatePacketLossCounter(unsigned int count);
void UpdatePacketTooLateCounter(); void UpdatePacketTooLateCounter();
@ -590,12 +586,8 @@ class PeerHandler
{ {
public: public:
PeerHandler() PeerHandler() = default;
{ virtual ~PeerHandler() = default;
}
virtual ~PeerHandler()
{
}
/* /*
This is called after the Peer has been inserted into the This is called after the Peer has been inserted into the
@ -612,7 +604,7 @@ public:
class PeerHelper class PeerHelper
{ {
public: public:
PeerHelper() {}; PeerHelper() = default;;
PeerHelper(Peer* peer); PeerHelper(Peer* peer);
~PeerHelper(); ~PeerHelper();
@ -744,7 +736,7 @@ class Peer {
float max_rtt = 0.0f; float max_rtt = 0.0f;
float avg_rtt = -1.0f; float avg_rtt = -1.0f;
rttstats() {}; rttstats() = default;
}; };
rttstats m_rtt; rttstats m_rtt;
@ -769,7 +761,7 @@ public:
friend class Connection; friend class Connection;
UDPPeer(u16 a_id, Address a_address, Connection* connection); UDPPeer(u16 a_id, Address a_address, Connection* connection);
virtual ~UDPPeer() {}; virtual ~UDPPeer() = default;
void PutReliableSendCommand(ConnectionCommand &c, void PutReliableSendCommand(ConnectionCommand &c,
unsigned int max_packet_size); unsigned int max_packet_size);
@ -841,7 +833,7 @@ struct ConnectionEvent
bool timeout = false; bool timeout = false;
Address address; Address address;
ConnectionEvent() {} ConnectionEvent() = default;
std::string describe() std::string describe()
{ {

View File

@ -30,7 +30,8 @@ class NetworkPacket
public: public:
NetworkPacket(u16 command, u32 datasize, u16 peer_id); NetworkPacket(u16 command, u32 datasize, u16 peer_id);
NetworkPacket(u16 command, u32 datasize); NetworkPacket(u16 command, u32 datasize);
NetworkPacket() {} NetworkPacket() = default;
~NetworkPacket(); ~NetworkPacket();
void putRawPacket(u8 *data, u32 datasize, u16 peer_id); void putRawPacket(u8 *data, u32 datasize, u16 peer_id);

View File

@ -173,7 +173,7 @@ void Server::handleCommand_Init(NetworkPacket* pkt)
return; return;
} }
if (string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS) == false) { if (!string_allowed(playerName, PLAYERNAME_ALLOWED_CHARS)) {
actionstream << "Server: Player with an invalid name " actionstream << "Server: Player with an invalid name "
<< "tried to connect from " << addr_s << std::endl; << "tried to connect from " << addr_s << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_WRONG_CHARS_IN_NAME); 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 << " " << "tried to connect from " << addr_s << " "
<< "but it was disallowed for the following reason: " << "but it was disallowed for the following reason: "
<< reason << std::endl; << reason << std::endl;
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING, DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_CUSTOM_STRING, reason);
reason.c_str());
return; return;
} }
} }
@ -468,7 +467,7 @@ void Server::handleCommand_Init_Legacy(NetworkPacket* pkt)
return; return;
} }
if (string_allowed(playername, PLAYERNAME_ALLOWED_CHARS) == false) { if (!string_allowed(playername, PLAYERNAME_ALLOWED_CHARS)) {
actionstream << "Server: Player with an invalid name " actionstream << "Server: Player with an invalid name "
<< "tried to connect from " << addr_s << std::endl; << "tried to connect from " << addr_s << std::endl;
DenyAccess_Legacy(pkt->getPeerId(), L"Name contains unallowed characters"); 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 << " " << "tried to connect from " << addr_s << " "
<< "but it was disallowed for the following reason: " << "but it was disallowed for the following reason: "
<< reason << std::endl; << reason << std::endl;
DenyAccess_Legacy(pkt->getPeerId(), utf8_to_wide(reason.c_str())); DenyAccess_Legacy(pkt->getPeerId(), utf8_to_wide(reason));
return; return;
} }
} }
@ -539,7 +538,7 @@ void Server::handleCommand_Init_Legacy(NetworkPacket* pkt)
if (!has_auth) { if (!has_auth) {
if (!isSingleplayer() && if (!isSingleplayer() &&
g_settings->getBool("disallow_empty_password") && g_settings->getBool("disallow_empty_password") &&
std::string(given_password) == "") { std::string(given_password).empty()) {
actionstream << "Server: " << playername actionstream << "Server: " << playername
<< " supplied empty password" << std::endl; << " supplied empty password" << std::endl;
DenyAccess_Legacy(pkt->getPeerId(), L"Empty passwords are " DenyAccess_Legacy(pkt->getPeerId(), L"Empty passwords are "
@ -1637,7 +1636,7 @@ void Server::handleCommand_Interact(NetworkPacket* pkt)
RemoteClient *client = getClient(pkt->getPeerId()); RemoteClient *client = getClient(pkt->getPeerId());
v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS)); v3s16 blockpos = getNodeBlockPos(floatToInt(pointed_pos_above, BS));
v3s16 blockpos2 = getNodeBlockPos(floatToInt(pointed_pos_under, 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); client->SetBlockNotSent(blockpos);
if (blockpos2 != blockpos) { if (blockpos2 != blockpos) {
client->SetBlockNotSent(blockpos2); client->SetBlockNotSent(blockpos2);
@ -1895,10 +1894,10 @@ void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
if (wantSudo) { if (wantSudo) {
DenySudoAccess(pkt->getPeerId()); DenySudoAccess(pkt->getPeerId());
return; return;
} else {
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
} }
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
} }
std::string bytes_A; std::string bytes_A;
@ -1967,10 +1966,10 @@ void Server::handleCommand_SrpBytesA(NetworkPacket* pkt)
if (wantSudo) { if (wantSudo) {
DenySudoAccess(pkt->getPeerId()); DenySudoAccess(pkt->getPeerId());
return; 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()); NetworkPacket resp_pkt(TOCLIENT_SRP_BYTES_S_B, 0, pkt->getPeerId());
@ -2004,10 +2003,10 @@ void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
if (wantSudo) { if (wantSudo) {
DenySudoAccess(pkt->getPeerId()); DenySudoAccess(pkt->getPeerId());
return; return;
} else {
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
} }
DenyAccess(pkt->getPeerId(), SERVER_ACCESSDENIED_UNEXPECTED_DATA);
return;
} }
std::string bytes_M; std::string bytes_M;
@ -2035,14 +2034,14 @@ void Server::handleCommand_SrpBytesM(NetworkPacket* pkt)
<< " (SRP) password for authentication." << std::endl; << " (SRP) password for authentication." << std::endl;
DenySudoAccess(pkt->getPeerId()); DenySudoAccess(pkt->getPeerId());
return; 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) { if (client->create_player_on_auth_success) {

View File

@ -48,7 +48,7 @@ private:
public: public:
LuaCamera(Camera *m); LuaCamera(Camera *m);
~LuaCamera() {} ~LuaCamera() = default;
static void create(lua_State *L, Camera *m); static void create(lua_State *L, Camera *m);

View File

@ -34,7 +34,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "util/string.h" #include "util/string.h"
#include "nodedef.h" #include "nodedef.h"
extern MainGameCallback *g_gamecallback;
int ModApiClient::l_get_current_modname(lua_State *L) int ModApiClient::l_get_current_modname(lua_State *L)
{ {

View File

@ -57,7 +57,7 @@ bool ModApiCraft::readCraftRecipeShaped(lua_State *L, int index,
// key at index -2 and value at index -1 // key at index -2 and value at index -1
if(!lua_isstring(L, -1)) if(!lua_isstring(L, -1))
return false; return false;
recipe.push_back(lua_tostring(L, -1)); recipe.emplace_back(lua_tostring(L, -1));
// removes value, keeps key for next iteration // removes value, keeps key for next iteration
lua_pop(L, 1); lua_pop(L, 1);
colcount++; colcount++;
@ -90,7 +90,7 @@ bool ModApiCraft::readCraftRecipeShapeless(lua_State *L, int index,
// key at index -2 and value at index -1 // key at index -2 and value at index -1
if(!lua_isstring(L, -1)) if(!lua_isstring(L, -1))
return false; return false;
recipe.push_back(lua_tostring(L, -1)); recipe.emplace_back(lua_tostring(L, -1));
// removes value, keeps key for next iteration // removes value, keeps key for next iteration
lua_pop(L, 1); lua_pop(L, 1);
} }
@ -122,8 +122,7 @@ bool ModApiCraft::readCraftReplacements(lua_State *L, int index,
return false; return false;
std::string replace_to = lua_tostring(L, -1); std::string replace_to = lua_tostring(L, -1);
lua_pop(L, 1); lua_pop(L, 1);
replacements.pairs.push_back( replacements.pairs.emplace_back(replace_from, replace_to);
std::make_pair(replace_from, replace_to));
// removes value, keeps key for next iteration // removes value, keeps key for next iteration
lua_pop(L, 1); lua_pop(L, 1);
} }
@ -148,7 +147,7 @@ int ModApiCraft::l_register_craft(lua_State *L)
*/ */
if(type == "shaped"){ if(type == "shaped"){
std::string output = getstringfield_default(L, table, "output", ""); std::string output = getstringfield_default(L, table, "output", "");
if(output == "") if (output.empty())
throw LuaError("Crafting definition is missing an output"); throw LuaError("Crafting definition is missing an output");
int width = 0; int width = 0;
@ -179,7 +178,7 @@ int ModApiCraft::l_register_craft(lua_State *L)
*/ */
else if(type == "shapeless"){ else if(type == "shapeless"){
std::string output = getstringfield_default(L, table, "output", ""); std::string output = getstringfield_default(L, table, "output", "");
if(output == "") if (output.empty())
throw LuaError("Crafting definition (shapeless)" throw LuaError("Crafting definition (shapeless)"
" is missing an output"); " is missing an output");
@ -222,12 +221,12 @@ int ModApiCraft::l_register_craft(lua_State *L)
*/ */
else if(type == "cooking"){ else if(type == "cooking"){
std::string output = getstringfield_default(L, table, "output", ""); std::string output = getstringfield_default(L, table, "output", "");
if(output == "") if (output.empty())
throw LuaError("Crafting definition (cooking)" throw LuaError("Crafting definition (cooking)"
" is missing an output"); " is missing an output");
std::string recipe = getstringfield_default(L, table, "recipe", ""); std::string recipe = getstringfield_default(L, table, "recipe", "");
if(recipe == "") if (recipe.empty())
throw LuaError("Crafting definition (cooking)" throw LuaError("Crafting definition (cooking)"
" is missing a recipe" " is missing a recipe"
" (output=\"" + output + "\")"); " (output=\"" + output + "\")");
@ -252,7 +251,7 @@ int ModApiCraft::l_register_craft(lua_State *L)
*/ */
else if(type == "fuel"){ else if(type == "fuel"){
std::string recipe = getstringfield_default(L, table, "recipe", ""); std::string recipe = getstringfield_default(L, table, "recipe", "");
if(recipe == "") if (recipe.empty())
throw LuaError("Crafting definition (fuel)" throw LuaError("Crafting definition (fuel)"
" is missing a recipe"); " 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 output = getstringfield_default(L, table, "output", "");
std::string type = getstringfield_default(L, table, "type", "shaped"); std::string type = getstringfield_default(L, table, "type", "shaped");
CraftOutput c_output(output, 0); CraftOutput c_output(output, 0);
if (output != "") { if (!output.empty()) {
if (craftdef->clearCraftRecipesByOutput(c_output, getServer(L))) if (craftdef->clearCraftRecipesByOutput(c_output, getServer(L)))
return 0; return 0;
else
throw LuaError("No craft recipe known for output" throw LuaError("No craft recipe known for output"
" (output=\"" + output + "\")"); " (output=\"" + output + "\")");
} }
std::vector<std::string> recipe; std::vector<std::string> recipe;
int width = 0; int width = 0;
@ -330,7 +329,7 @@ int ModApiCraft::l_clear_craft(lua_State *L)
else if (type == "cooking") { else if (type == "cooking") {
method = CRAFT_METHOD_COOKING; method = CRAFT_METHOD_COOKING;
std::string rec = getstringfield_default(L, table, "recipe", ""); std::string rec = getstringfield_default(L, table, "recipe", "");
if (rec == "") if (rec.empty())
throw LuaError("Crafting definition (cooking)" throw LuaError("Crafting definition (cooking)"
" is missing a recipe"); " is missing a recipe");
recipe.push_back(rec); recipe.push_back(rec);
@ -341,7 +340,7 @@ int ModApiCraft::l_clear_craft(lua_State *L)
else if (type == "fuel") { else if (type == "fuel") {
method = CRAFT_METHOD_FUEL; method = CRAFT_METHOD_FUEL;
std::string rec = getstringfield_default(L, table, "recipe", ""); std::string rec = getstringfield_default(L, table, "recipe", "");
if (rec == "") if (rec.empty())
throw LuaError("Crafting definition (fuel)" throw LuaError("Crafting definition (fuel)"
" is missing a recipe"); " is missing a recipe");
recipe.push_back(rec); recipe.push_back(rec);

View File

@ -743,9 +743,8 @@ int ModApiEnvMod::l_find_node_near(lua_State *L)
for (int d = start_radius; d <= radius; d++) { for (int d = start_radius; d <= radius; d++) {
std::vector<v3s16> list = FacePositionCache::getFacePositions(d); std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
for (std::vector<v3s16>::iterator i = list.begin(); for (v3s16 i : list) {
i != list.end(); ++i) { v3s16 p = pos + i;
v3s16 p = pos + (*i);
content_t c = env->getMap().getNodeNoEx(p).getContent(); content_t c = env->getMap().getNodeNoEx(p).getContent();
if (filter.count(c) != 0) { if (filter.count(c) != 0) {
push_v3s16(L, p); push_v3s16(L, p);
@ -809,10 +808,9 @@ int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
} }
} }
lua_newtable(L); lua_newtable(L);
for (std::set<content_t>::const_iterator it = filter.begin(); for (content_t it : filter) {
it != filter.end(); ++it) { lua_pushnumber(L, individual_count[it]);
lua_pushnumber(L, individual_count[*it]); lua_setfield(L, -2, ndef->get(it).name.c_str());
lua_setfield(L, -2, ndef->get(*it).name.c_str());
} }
return 2; 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++) { for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
success = success & map.repairBlockLight(blockpos, &modified_blocks); success = success & map.repairBlockLight(blockpos, &modified_blocks);
} }
if (modified_blocks.size() > 0) { if (!modified_blocks.empty()) {
MapEditEvent event; MapEditEvent event;
event.type = MEET_OTHER; event.type = MEET_OTHER;
for (std::map<v3s16, MapBlock *>::iterator it = modified_blocks.begin(); for (auto &modified_block : modified_blocks)
it != modified_blocks.end(); ++it) event.modified_blocks.insert(modified_block.first);
event.modified_blocks.insert(it->first);
map.dispatchEvent(&event); map.dispatchEvent(&event);
} }
@ -1126,14 +1123,13 @@ int ModApiEnvMod::l_find_path(lua_State *L)
std::vector<v3s16> path = get_path(env, pos1, pos2, std::vector<v3s16> path = get_path(env, pos1, pos2,
searchdistance, max_jump, max_drop, algo); searchdistance, max_jump, max_drop, algo);
if (path.size() > 0) if (!path.empty()) {
{
lua_newtable(L); lua_newtable(L);
int top = lua_gettop(L); int top = lua_gettop(L);
unsigned int index = 1; unsigned int index = 1;
for (std::vector<v3s16>::iterator i = path.begin(); i != path.end(); ++i) { for (v3s16 i : path) {
lua_pushnumber(L,index); lua_pushnumber(L,index);
push_v3s16(L, *i); push_v3s16(L, i);
lua_settable(L, top); lua_settable(L, top);
index++; index++;
} }
@ -1167,8 +1163,7 @@ int ModApiEnvMod::l_spawn_tree(lua_State *L)
tree_def.leavesnode=ndef->getId(leaves); tree_def.leavesnode=ndef->getId(leaves);
tree_def.leaves2_chance=0; tree_def.leaves2_chance=0;
getstringfield(L, 2, "leaves2", leaves); getstringfield(L, 2, "leaves2", leaves);
if (leaves !="") if (!leaves.empty()) {
{
tree_def.leaves2node=ndef->getId(leaves); tree_def.leaves2node=ndef->getId(leaves);
getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance); 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); getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
tree_def.fruit_chance=0; tree_def.fruit_chance=0;
getstringfield(L, 2, "fruit", fruit); getstringfield(L, 2, "fruit", fruit);
if (fruit != "") if (!fruit.empty()) {
{
tree_def.fruitnode=ndef->getId(fruit); tree_def.fruitnode=ndef->getId(fruit);
getintfield(L, 2, "fruit_chance",tree_def.fruit_chance); getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
} }

View File

@ -69,7 +69,7 @@ void ModApiHttp::read_http_fetch_request(lua_State *L, HTTPFetchRequest &req)
while (lua_next(L, 2) != 0) while (lua_next(L, 2) != 0)
{ {
const char *header = luaL_checkstring(L, -1); const char *header = luaL_checkstring(L, -1);
req.extra_headers.push_back(header); req.extra_headers.emplace_back(header);
lua_pop(L, 1); lua_pop(L, 1);
} }
} }

View File

@ -409,10 +409,6 @@ InvRef::InvRef(const InventoryLocation &loc):
{ {
} }
InvRef::~InvRef()
{
}
// Creates an InvRef and leaves it on top of stack // Creates an InvRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side. // Not callable from Lua; all references are created on the C side.
void InvRef::create(lua_State *L, const InventoryLocation &loc) void InvRef::create(lua_State *L, const InventoryLocation &loc)

View File

@ -106,7 +106,7 @@ private:
public: public:
InvRef(const InventoryLocation &loc); InvRef(const InventoryLocation &loc);
~InvRef(); ~InvRef() = default;
// Creates an InvRef and leaves it on top of stack // Creates an InvRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side. // Not callable from Lua; all references are created on the C side.

View File

@ -67,7 +67,7 @@ int LuaItemStack::l_set_name(lua_State *L)
bool status = true; bool status = true;
item.name = luaL_checkstring(L, 2); item.name = luaL_checkstring(L, 2);
if (item.name == "" || item.empty()) { if (item.name.empty() || item.empty()) {
item.clear(); item.clear();
status = false; status = false;
} }
@ -231,12 +231,11 @@ int LuaItemStack::l_to_table(lua_State *L)
lua_newtable(L); lua_newtable(L);
const StringMap &fields = item.metadata.getStrings(); const StringMap &fields = item.metadata.getStrings();
for (StringMap::const_iterator it = fields.begin(); for (const auto &field : fields) {
it != fields.end(); ++it) { const std::string &name = field.first;
const std::string &name = it->first;
if (name.empty()) if (name.empty())
continue; continue;
const std::string &value = it->second; const std::string &value = field.second;
lua_pushlstring(L, name.c_str(), name.size()); lua_pushlstring(L, name.c_str(), name.size());
lua_pushlstring(L, value.c_str(), value.size()); lua_pushlstring(L, value.c_str(), value.size());
lua_settable(L, -3); lua_settable(L, -3);
@ -391,10 +390,6 @@ LuaItemStack::LuaItemStack(const ItemStack &item):
{ {
} }
LuaItemStack::~LuaItemStack()
{
}
const ItemStack& LuaItemStack::getItem() const const ItemStack& LuaItemStack::getItem() const
{ {
return m_stack; return m_stack;

View File

@ -121,7 +121,7 @@ private:
public: public:
LuaItemStack(const ItemStack &item); LuaItemStack(const ItemStack &item);
~LuaItemStack(); ~LuaItemStack() = default;
const ItemStack& getItem() const; const ItemStack& getItem() const;
ItemStack& getItem(); ItemStack& getItem();

View File

@ -46,7 +46,7 @@ private:
static int gc_object(lua_State *L); static int gc_object(lua_State *L);
public: public:
ItemStackMetaRef(ItemStack *istack): istack(istack) {} ItemStackMetaRef(ItemStack *istack): istack(istack) {}
~ItemStackMetaRef() {} ~ItemStackMetaRef() = default;
// Creates an ItemStackMetaRef and leaves it on top of stack // Creates an ItemStackMetaRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side. // Not callable from Lua; all references are created on the C side.

View File

@ -70,7 +70,7 @@ private:
public: public:
LuaLocalPlayer(LocalPlayer *m); LuaLocalPlayer(LocalPlayer *m);
~LuaLocalPlayer() {} ~LuaLocalPlayer() = default;
static void create(lua_State *L, LocalPlayer *m); static void create(lua_State *L, LocalPlayer *m);

View File

@ -51,7 +51,7 @@ private:
public: public:
LuaMinimap(Minimap *m); LuaMinimap(Minimap *m);
~LuaMinimap() {} ~LuaMinimap() = default;
static void create(lua_State *L, Minimap *object); static void create(lua_State *L, Minimap *object);

View File

@ -182,10 +182,6 @@ NodeMetaRef::NodeMetaRef(Metadata *meta):
{ {
} }
NodeMetaRef::~NodeMetaRef()
{
}
// Creates an NodeMetaRef and leaves it on top of stack // Creates an NodeMetaRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side. // Not callable from Lua; all references are created on the C side.
void NodeMetaRef::create(lua_State *L, v3s16 p, ServerEnvironment *env) void NodeMetaRef::create(lua_State *L, v3s16 p, ServerEnvironment *env)

View File

@ -80,7 +80,7 @@ public:
NodeMetaRef(v3s16 p, ServerEnvironment *env); NodeMetaRef(v3s16 p, ServerEnvironment *env);
NodeMetaRef(Metadata *meta); NodeMetaRef(Metadata *meta);
~NodeMetaRef(); ~NodeMetaRef() = default;
// Creates an NodeMetaRef and leaves it on top of stack // Creates an NodeMetaRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side. // Not callable from Lua; all references are created on the C side.

View File

@ -113,10 +113,6 @@ NodeTimerRef::NodeTimerRef(v3s16 p, ServerEnvironment *env):
{ {
} }
NodeTimerRef::~NodeTimerRef()
{
}
// Creates an NodeTimerRef and leaves it on top of stack // Creates an NodeTimerRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side. // Not callable from Lua; all references are created on the C side.
void NodeTimerRef::create(lua_State *L, v3s16 p, ServerEnvironment *env) void NodeTimerRef::create(lua_State *L, v3s16 p, ServerEnvironment *env)

View File

@ -51,7 +51,7 @@ private:
public: public:
NodeTimerRef(v3s16 p, ServerEnvironment *env); NodeTimerRef(v3s16 p, ServerEnvironment *env);
~NodeTimerRef(); ~NodeTimerRef() = default;
// Creates an NodeTimerRef and leaves it on top of stack // Creates an NodeTimerRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side. // Not callable from Lua; all references are created on the C side.

View File

@ -36,11 +36,6 @@ LuaPerlinNoise::LuaPerlinNoise(NoiseParams *params) :
} }
LuaPerlinNoise::~LuaPerlinNoise()
{
}
int LuaPerlinNoise::l_get2d(lua_State *L) int LuaPerlinNoise::l_get2d(lua_State *L)
{ {
NO_MAP_LOCK_REQUIRED; NO_MAP_LOCK_REQUIRED;

View File

@ -43,7 +43,7 @@ private:
public: public:
LuaPerlinNoise(NoiseParams *params); LuaPerlinNoise(NoiseParams *params);
~LuaPerlinNoise(); ~LuaPerlinNoise() = default;
// LuaPerlinNoise(seed, octaves, persistence, scale) // LuaPerlinNoise(seed, octaves, persistence, scale)
// Creates an LuaPerlinNoise and leaves it on top of stack // Creates an LuaPerlinNoise and leaves it on top of stack

View File

@ -551,8 +551,8 @@ int ObjectRef::l_get_local_animation(lua_State *L)
float frame_speed; float frame_speed;
player->getLocalAnimations(frames, &frame_speed); player->getLocalAnimations(frames, &frame_speed);
for (int i = 0; i < 4; i++) { for (v2s32 frame : frames) {
push_v2s32(L, frames[i]); push_v2s32(L, frame);
} }
lua_pushnumber(L, frame_speed); lua_pushnumber(L, frame_speed);
@ -611,7 +611,7 @@ int ObjectRef::l_set_bone_position(lua_State *L)
ServerActiveObject *co = getobject(ref); ServerActiveObject *co = getobject(ref);
if (co == NULL) return 0; if (co == NULL) return 0;
// Do it // Do it
std::string bone = ""; std::string bone;
if (!lua_isnil(L, 2)) if (!lua_isnil(L, 2))
bone = lua_tostring(L, 2); bone = lua_tostring(L, 2);
v3f position = v3f(0, 0, 0); v3f position = v3f(0, 0, 0);
@ -633,7 +633,7 @@ int ObjectRef::l_get_bone_position(lua_State *L)
if (co == NULL) if (co == NULL)
return 0; return 0;
// Do it // Do it
std::string bone = ""; std::string bone;
if (!lua_isnil(L, 2)) if (!lua_isnil(L, 2))
bone = lua_tostring(L, 2); bone = lua_tostring(L, 2);
@ -661,7 +661,7 @@ int ObjectRef::l_set_attach(lua_State *L)
return 0; return 0;
// Do it // Do it
int parent_id = 0; int parent_id = 0;
std::string bone = ""; std::string bone;
v3f position = v3f(0, 0, 0); v3f position = v3f(0, 0, 0);
v3f rotation = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0);
co->getAttachment(&parent_id, &bone, &position, &rotation); co->getAttachment(&parent_id, &bone, &position, &rotation);
@ -696,7 +696,7 @@ int ObjectRef::l_get_attach(lua_State *L)
// Do it // Do it
int parent_id = 0; int parent_id = 0;
std::string bone = ""; std::string bone;
v3f position = v3f(0, 0, 0); v3f position = v3f(0, 0, 0);
v3f rotation = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0);
co->getAttachment(&parent_id, &bone, &position, &rotation); co->getAttachment(&parent_id, &bone, &position, &rotation);
@ -722,7 +722,7 @@ int ObjectRef::l_set_detach(lua_State *L)
return 0; return 0;
int parent_id = 0; int parent_id = 0;
std::string bone = ""; std::string bone;
v3f position; v3f position;
v3f rotation; v3f rotation;
co->getAttachment(&parent_id, &bone, &position, &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 attr = luaL_checkstring(L, 2);
std::string value = ""; std::string value;
if (co->getExtendedAttribute(attr, &value)) { if (co->getExtendedAttribute(attr, &value)) {
lua_pushstring(L, value.c_str()); lua_pushstring(L, value.c_str());
return 1; return 1;
@ -1684,9 +1684,9 @@ int ObjectRef::l_set_sky(lua_State *L)
while (lua_next(L, 4) != 0) { while (lua_next(L, 4) != 0) {
// key at index -2 and value at index -1 // key at index -2 and value at index -1
if (lua_isstring(L, -1)) if (lua_isstring(L, -1))
params.push_back(lua_tostring(L, -1)); params.emplace_back(lua_tostring(L, -1));
else else
params.push_back(""); params.emplace_back("");
// removes value, keeps key for next iteration // removes value, keeps key for next iteration
lua_pop(L, 1); lua_pop(L, 1);
} }
@ -1720,15 +1720,14 @@ int ObjectRef::l_get_sky(lua_State *L)
bool clouds; bool clouds;
player->getSky(&bgcolor, &type, &params, &clouds); player->getSky(&bgcolor, &type, &params, &clouds);
type = type == "" ? "regular" : type; type = type.empty() ? "regular" : type;
push_ARGB8(L, bgcolor); push_ARGB8(L, bgcolor);
lua_pushlstring(L, type.c_str(), type.size()); lua_pushlstring(L, type.c_str(), type.size());
lua_newtable(L); lua_newtable(L);
s16 i = 1; s16 i = 1;
for (std::vector<std::string>::iterator it = params.begin(); for (const std::string &param : params) {
it != params.end(); ++it) { lua_pushlstring(L, param.c_str(), param.size());
lua_pushlstring(L, it->c_str(), it->size());
lua_rawseti(L, -2, i); lua_rawseti(L, -2, i);
i++; i++;
} }
@ -1865,15 +1864,6 @@ ObjectRef::ObjectRef(ServerActiveObject *object):
//infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl; //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 // Creates an ObjectRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side. // Not callable from Lua; all references are created on the C side.
void ObjectRef::create(lua_State *L, ServerActiveObject *object) void ObjectRef::create(lua_State *L, ServerActiveObject *object)

View File

@ -35,7 +35,7 @@ class ObjectRef : public ModApiBase {
public: public:
ObjectRef(ServerActiveObject *object); ObjectRef(ServerActiveObject *object);
~ObjectRef(); ~ObjectRef() = default;
// Creates an ObjectRef and leaves it on top of stack // Creates an ObjectRef and leaves it on top of stack
// Not callable from Lua; all references are created on the C side. // Not callable from Lua; all references are created on the C side.

View File

@ -53,8 +53,8 @@ int ModApiParticles::l_add_particle(lua_State *L)
struct TileAnimationParams animation; struct TileAnimationParams animation;
animation.type = TAT_NONE; animation.type = TAT_NONE;
std::string texture = ""; std::string texture;
std::string playername = ""; std::string playername;
u8 glow = 0; u8 glow = 0;
@ -158,8 +158,8 @@ int ModApiParticles::l_add_particlespawner(lua_State *L)
struct TileAnimationParams animation; struct TileAnimationParams animation;
animation.type = TAT_NONE; animation.type = TAT_NONE;
ServerActiveObject *attached = NULL; ServerActiveObject *attached = NULL;
std::string texture = ""; std::string texture;
std::string playername = ""; std::string playername;
u8 glow = 0; u8 glow = 0;
if (lua_gettop(L) > 1) //deprecated if (lua_gettop(L) > 1) //deprecated
@ -262,7 +262,7 @@ int ModApiParticles::l_delete_particlespawner(lua_State *L)
// Get parameters // Get parameters
u32 id = luaL_checknumber(L, 1); u32 id = luaL_checknumber(L, 1);
std::string playername = ""; std::string playername;
if (lua_gettop(L) == 2) { if (lua_gettop(L) == 2) {
playername = luaL_checkstring(L, 2); playername = luaL_checkstring(L, 2);
} }

View File

@ -198,10 +198,9 @@ int LuaSettings::l_to_table(lua_State* L)
std::vector<std::string> keys = o->m_settings->getNames(); std::vector<std::string> keys = o->m_settings->getNames();
lua_newtable(L); lua_newtable(L);
for (unsigned int i=0; i < keys.size(); i++) for (const std::string &key : keys) {
{ lua_pushstring(L, o->m_settings->get(key).c_str());
lua_pushstring(L, o->m_settings->get(keys[i]).c_str()); lua_setfield(L, -2, key.c_str());
lua_setfield(L, -2, keys[i].c_str());
} }
return 1; return 1;

View File

@ -50,7 +50,7 @@ private:
public: public:
StorageRef(ModMetadata *object); StorageRef(ModMetadata *object);
~StorageRef() {} ~StorageRef() = default;
static void Register(lua_State *L); static void Register(lua_State *L);
static void create(lua_State *L, ModMetadata *object); static void create(lua_State *L, ModMetadata *object);

View File

@ -344,9 +344,9 @@ int ModApiUtil::l_get_dir_list(lua_State *L)
int index = 0; int index = 0;
lua_newtable(L); lua_newtable(L);
for (size_t i = 0; i < list.size(); i++) { for (const fs::DirListNode &dln : list) {
if (list_all || list_dirs == list[i].dir) { if (list_all || list_dirs == dln.dir) {
lua_pushstring(L, list[i].name.c_str()); lua_pushstring(L, dln.name.c_str());
lua_rawseti(L, -2, ++index); lua_rawseti(L, -2, ++index);
} }
} }
@ -414,7 +414,7 @@ int ModApiUtil::l_get_version(lua_State *L)
lua_pushstring(L, g_version_string); lua_pushstring(L, g_version_string);
lua_setfield(L, table, "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_pushstring(L, g_version_hash);
lua_setfield(L, table, "hash"); lua_setfield(L, table, "hash");
} }

View File

@ -111,7 +111,7 @@ int LuaVoxelManip::l_write_to_map(lua_State *L)
MAP_LOCK_REQUIRED; MAP_LOCK_REQUIRED;
LuaVoxelManip *o = checkobject(L, 1); 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; GET_ENV_PTR;
ServerMap *map = &(env->getServerMap()); ServerMap *map = &(env->getServerMap());
if (o->is_mapgen_vm || !update_light) { if (o->is_mapgen_vm || !update_light) {
@ -123,9 +123,8 @@ int LuaVoxelManip::l_write_to_map(lua_State *L)
MapEditEvent event; MapEditEvent event;
event.type = MEET_OTHER; event.type = MEET_OTHER;
for (std::map<v3s16, MapBlock *>::iterator it = o->modified_blocks.begin(); for (const auto &modified_block : o->modified_blocks)
it != o->modified_blocks.end(); ++it) event.modified_blocks.insert(modified_block.first);
event.modified_blocks.insert(it->first);
map->dispatchEvent(&event); map->dispatchEvent(&event);
@ -198,7 +197,7 @@ int LuaVoxelManip::l_calc_lighting(lua_State *L)
v3s16 fpmax = vm->m_area.MaxEdge; v3s16 fpmax = vm->m_area.MaxEdge;
v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : fpmin + yblock; v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) : fpmin + yblock;
v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) : fpmax - 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); sortBoxVerticies(pmin, pmax);
if (!vm->m_area.contains(VoxelArea(pmin, pmax))) if (!vm->m_area.contains(VoxelArea(pmin, pmax)))

View File

@ -498,7 +498,7 @@ void ServerEnvironment::saveLoadedPlayers()
fs::CreateDir(players_path); fs::CreateDir(players_path);
for (RemotePlayer *player : m_players) { for (RemotePlayer *player : m_players) {
if (player->checkModified() || (player->getPlayerSAO() && if (player->checkModified() || (player->getPlayerSAO() &&
player->getPlayerSAO()->extendedAttributesModified())) { player->getPlayerSAO()->extendedAttributesModified())) {
try { try {
m_player_database->savePlayer(player); m_player_database->savePlayer(player);

View File

@ -35,6 +35,8 @@ public:
Semaphore(int val = 0); Semaphore(int val = 0);
~Semaphore(); ~Semaphore();
DISABLE_CLASS_COPY(Semaphore);
void post(unsigned int num = 1); void post(unsigned int num = 1);
void wait(); void wait();
bool wait(unsigned int time_ms); bool wait(unsigned int time_ms);
@ -47,6 +49,4 @@ private:
#else #else
sem_t semaphore; sem_t semaphore;
#endif #endif
DISABLE_CLASS_COPY(Semaphore);
}; };

View File

@ -31,7 +31,7 @@ class TestFailedException : public std::exception {
}; };
// Runs a unit test and reports results // Runs a unit test and reports results
#define TEST(fxn, ...) do { \ #define TEST(fxn, ...) { \
u64 t1 = porting::getTimeMs(); \ u64 t1 = porting::getTimeMs(); \
try { \ try { \
fxn(__VA_ARGS__); \ fxn(__VA_ARGS__); \
@ -47,21 +47,20 @@ class TestFailedException : public std::exception {
num_tests_run++; \ num_tests_run++; \
u64 tdiff = porting::getTimeMs() - t1; \ u64 tdiff = porting::getTimeMs() - t1; \
rawstream << #fxn << " - " << tdiff << "ms" << std::endl; \ rawstream << #fxn << " - " << tdiff << "ms" << std::endl; \
} while (0) }
// Asserts the specified condition is true, or fails the current unit test // Asserts the specified condition is true, or fails the current unit test
#define UASSERT(x) do { \ #define UASSERT(x) \
if (!(x)) { \ if (!(x)) { \
rawstream << "Test assertion failed: " #x << std::endl \ rawstream << "Test assertion failed: " #x << std::endl \
<< " at " << fs::GetFilenameFromPath(__FILE__) \ << " at " << fs::GetFilenameFromPath(__FILE__) \
<< ":" << __LINE__ << std::endl; \ << ":" << __LINE__ << std::endl; \
throw TestFailedException(); \ throw TestFailedException(); \
} \ }
} while (0)
// Asserts the specified condition is true, or fails the current unit test // Asserts the specified condition is true, or fails the current unit test
// and prints the format specifier fmt // and prints the format specifier fmt
#define UTEST(x, fmt, ...) do { \ #define UTEST(x, fmt, ...) \
if (!(x)) { \ if (!(x)) { \
char utest_buf[1024]; \ char utest_buf[1024]; \
snprintf(utest_buf, sizeof(utest_buf), fmt, __VA_ARGS__); \ snprintf(utest_buf, sizeof(utest_buf), fmt, __VA_ARGS__); \
@ -69,8 +68,7 @@ class TestFailedException : public std::exception {
<< " at " << fs::GetFilenameFromPath(__FILE__) \ << " at " << fs::GetFilenameFromPath(__FILE__) \
<< ":" << __LINE__ << std::endl; \ << ":" << __LINE__ << std::endl; \
throw TestFailedException(); \ throw TestFailedException(); \
} \ }
} while (0)
// Asserts the comparison specified by CMP is true, or fails the current unit test // Asserts the comparison specified by CMP is true, or fails the current unit test
#define UASSERTCMP(T, CMP, actual, expected) do { \ #define UASSERTCMP(T, CMP, actual, expected) do { \

View File

@ -109,28 +109,28 @@ void TestNodeResolver::testNodeResolving(IWritableNodeDefManager *ndef)
Foobar foobar; Foobar foobar;
size_t i; 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.emplace_back("default:dirt_with_grass");
foobar.m_nodenames.push_back("default:water"); foobar.m_nodenames.emplace_back("default:water");
foobar.m_nodenames.push_back("default:abloobloobloo"); foobar.m_nodenames.emplace_back("default:abloobloobloo");
foobar.m_nodenames.push_back("default:stone"); foobar.m_nodenames.emplace_back("default:stone");
foobar.m_nodenames.push_back("default:shmegoldorf"); foobar.m_nodenames.emplace_back("default:shmegoldorf");
foobar.m_nnlistsizes.push_back(5); 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_nnlistsizes.push_back(1);
foobar.m_nodenames.push_back("default:warf"); foobar.m_nodenames.emplace_back("default:warf");
foobar.m_nodenames.push_back("default:stone"); foobar.m_nodenames.emplace_back("default:stone");
foobar.m_nodenames.push_back("default:bloop"); foobar.m_nodenames.emplace_back("default:bloop");
foobar.m_nnlistsizes.push_back(3); foobar.m_nnlistsizes.push_back(3);
foobar.m_nnlistsizes.push_back(0); foobar.m_nnlistsizes.push_back(0);
foobar.m_nodenames.push_back("default:brick"); foobar.m_nodenames.emplace_back("default:brick");
foobar.m_nodenames.push_back("default:desert_stone"); foobar.m_nodenames.emplace_back("default:desert_stone");
foobar.m_nodenames.push_back("default:shnitzle"); foobar.m_nodenames.emplace_back("default:shnitzle");
ndef->pendNodeResolve(&foobar); ndef->pendNodeResolve(&foobar);
UASSERT(foobar.m_ndef == ndef); UASSERT(foobar.m_ndef == ndef);
@ -187,15 +187,15 @@ void TestNodeResolver::testPendingResolveCancellation(IWritableNodeDefManager *n
Foobaz foobaz1; Foobaz foobaz1;
foobaz1.test_content1 = 1234; foobaz1.test_content1 = 1234;
foobaz1.test_content2 = 5678; foobaz1.test_content2 = 5678;
foobaz1.m_nodenames.push_back("default:dirt_with_grass"); foobaz1.m_nodenames.emplace_back("default:dirt_with_grass");
foobaz1.m_nodenames.push_back("default:abloobloobloo"); foobaz1.m_nodenames.emplace_back("default:abloobloobloo");
ndef->pendNodeResolve(&foobaz1); ndef->pendNodeResolve(&foobaz1);
Foobaz foobaz2; Foobaz foobaz2;
foobaz2.test_content1 = 1234; foobaz2.test_content1 = 1234;
foobaz2.test_content2 = 5678; foobaz2.test_content2 = 5678;
foobaz2.m_nodenames.push_back("default:dirt_with_grass"); foobaz2.m_nodenames.emplace_back("default:dirt_with_grass");
foobaz2.m_nodenames.push_back("default:abloobloobloo"); foobaz2.m_nodenames.emplace_back("default:abloobloobloo");
ndef->pendNodeResolve(&foobaz2); ndef->pendNodeResolve(&foobaz2);
ndef->cancelNodeResolveCallback(&foobaz1); ndef->cancelNodeResolveCallback(&foobaz1);

View File

@ -67,10 +67,10 @@ void TestSchematic::testMtsSerializeDeserialize(INodeDefManager *ndef)
std::ios_base::in | std::ios_base::out); std::ios_base::in | std::ios_base::out);
std::vector<std::string> names; std::vector<std::string> names;
names.push_back("foo"); names.emplace_back("foo");
names.push_back("bar"); names.emplace_back("bar");
names.push_back("baz"); names.emplace_back("baz");
names.push_back("qux"); names.emplace_back("qux");
Schematic schem, schem2; Schematic schem, schem2;
@ -121,9 +121,9 @@ void TestSchematic::testLuaTableSerialize(INodeDefManager *ndef)
schem.slice_probs[y] = MTSCHEM_PROB_ALWAYS; schem.slice_probs[y] = MTSCHEM_PROB_ALWAYS;
std::vector<std::string> names; std::vector<std::string> names;
names.push_back("air"); names.emplace_back("air");
names.push_back("default:lava_source"); names.emplace_back("default:lava_source");
names.push_back("default:glass"); names.emplace_back("default:glass");
std::ostringstream ss(std::ios_base::binary); std::ostringstream ss(std::ios_base::binary);

View File

@ -166,16 +166,16 @@ void TestThreading::testAtomicSemaphoreThread()
static const u8 num_threads = 4; static const u8 num_threads = 4;
AtomicTestThread *threads[num_threads]; AtomicTestThread *threads[num_threads];
for (u8 i = 0; i < num_threads; ++i) { for (auto &thread : threads) {
threads[i] = new AtomicTestThread(val, trigger); thread = new AtomicTestThread(val, trigger);
UASSERT(threads[i]->start()); UASSERT(thread->start());
} }
trigger.post(num_threads); trigger.post(num_threads);
for (u8 i = 0; i < num_threads; ++i) { for (AtomicTestThread *thread : threads) {
threads[i]->wait(); thread->wait();
delete threads[i]; delete thread;
} }
UASSERT(val == num_threads * 0x10000); UASSERT(val == num_threads * 0x10000);

View File

@ -61,8 +61,8 @@ void TestVoxelManipulator::testVoxelArea()
// Correct results // Correct results
std::vector<VoxelArea> results; std::vector<VoxelArea> results;
results.push_back(VoxelArea(v3s16(-2,-2,-3), v3s16(3,2,-3))); results.emplace_back(v3s16(-2,-2,-3), v3s16(3,2,-3));
results.push_back(VoxelArea(v3s16(3,-2,-2), v3s16(3,2,2))); results.emplace_back(v3s16(3,-2,-2), v3s16(3,2,2));
UASSERT(aa.size() == results.size()); UASSERT(aa.size() == results.size());

View File

@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "base64.h" #include "base64.h"
#include "sha1.h" #include "sha1.h"
#include "srp.h" #include "srp.h"
#include "string.h" #include "util/string.h"
#include "debug.h" #include "debug.h"
// Get an sha-1 hash of the player's name combined with // Get an sha-1 hash of the player's name combined with

View File

@ -40,8 +40,9 @@ static inline bool is_base64(unsigned char c) {
bool base64_is_valid(std::string const& s) bool base64_is_valid(std::string const& s)
{ {
for(size_t i=0; i<s.size(); i++) for (char i : s)
if(!is_base64(s[i])) return false; if (!is_base64(i))
return false;
return true; return true;
} }

View File

@ -79,7 +79,7 @@ template<typename Key, typename Value>
class MutexedMap class MutexedMap
{ {
public: public:
MutexedMap() {} MutexedMap() = default;
void set(const Key &name, const Value &value) void set(const Key &name, const Value &value)
{ {
@ -128,7 +128,8 @@ public:
template<typename Key, typename U, typename Caller, typename CallerData> template<typename Key, typename U, typename Caller, typename CallerData>
friend class RequestQueue; friend class RequestQueue;
MutexedQueue() {} MutexedQueue() = default;
bool empty() const bool empty() const
{ {
MutexAutoLock lock(m_mutex); MutexAutoLock lock(m_mutex);
@ -153,9 +154,9 @@ public:
T t = m_queue.front(); T t = m_queue.front();
m_queue.pop_front(); m_queue.pop_front();
return t; return t;
} else {
return T();
} }
return T();
} }
T pop_front(u32 wait_time_max_ms) T pop_front(u32 wait_time_max_ms)
@ -166,9 +167,9 @@ public:
T t = m_queue.front(); T t = m_queue.front();
m_queue.pop_front(); m_queue.pop_front();
return t; return t;
} else {
throw ItemNotFoundException("MutexedQueue: queue is empty");
} }
throw ItemNotFoundException("MutexedQueue: queue is empty");
} }
T pop_frontNoEx() T pop_frontNoEx()
@ -190,9 +191,9 @@ public:
T t = m_queue.back(); T t = m_queue.back();
m_queue.pop_back(); m_queue.pop_back();
return t; 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. /* this version of pop_back returns a empty element of T on timeout.
@ -206,9 +207,9 @@ public:
T t = m_queue.back(); T t = m_queue.back();
m_queue.pop_back(); m_queue.pop_back();
return t; return t;
} else {
return T();
} }
return T();
} }
T pop_backNoEx() T pop_backNoEx()

View File

@ -23,7 +23,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include "../constants.h" // BS, MAP_BLOCKSIZE #include "../constants.h" // BS, MAP_BLOCKSIZE
#include "../noise.h" // PseudoRandom, PcgRandom #include "../noise.h" // PseudoRandom, PcgRandom
#include "../threading/mutex_auto_lock.h" #include "../threading/mutex_auto_lock.h"
#include <string.h> #include <cstring>
// myrand // myrand

View File

@ -81,7 +81,7 @@ struct PointedThing
f32 distanceSq = 0; f32 distanceSq = 0;
//! Constructor for POINTEDTHING_NOTHING //! Constructor for POINTEDTHING_NOTHING
PointedThing() {}; PointedThing() = default;
//! Constructor for POINTEDTHING_NODE //! Constructor for POINTEDTHING_NODE
PointedThing(const v3s16 &under, const v3s16 &above, PointedThing(const v3s16 &under, const v3s16 &above,
const v3s16 &real_under, const v3f &point, const v3s16 &normal, const v3s16 &real_under, const v3f &point, const v3s16 &normal,

View File

@ -156,8 +156,8 @@ std::string serializeWideString(const std::wstring &plain)
writeU16((u8 *)buf, plain.size()); writeU16((u8 *)buf, plain.size());
s.append(buf, 2); s.append(buf, 2);
for (u32 i = 0; i < plain.size(); i++) { for (wchar_t i : plain) {
writeU16((u8 *)buf, plain[i]); writeU16((u8 *)buf, i);
s.append(buf, 2); s.append(buf, 2);
} }
return s; return s;
@ -246,8 +246,7 @@ std::string serializeJsonString(const std::string &plain)
std::ostringstream os(std::ios::binary); std::ostringstream os(std::ios::binary);
os << "\""; os << "\"";
for (size_t i = 0; i < plain.size(); i++) { for (char c : plain) {
char c = plain[i];
switch (c) { switch (c) {
case '"': case '"':
os << "\\\""; os << "\\\"";
@ -308,7 +307,9 @@ std::string deSerializeJsonString(std::istream &is)
if (c == '"') { if (c == '"') {
return os.str(); return os.str();
} else if (c == '\\') { }
if (c == '\\') {
c2 = is.get(); c2 = is.get();
if (is.eof()) if (is.eof())
throw SerializationError("JSON string ended prematurely"); throw SerializationError("JSON string ended prematurely");
@ -390,17 +391,18 @@ std::string deSerializeJsonStringIfNeeded(std::istream &is)
// Found end of word // Found end of word
is.unget(); is.unget();
break; break;
} else {
tmp_os << c;
} }
tmp_os << c;
} }
expect_initial_quote = false; expect_initial_quote = false;
} }
if (is_json) { if (is_json) {
std::istringstream tmp_is(tmp_os.str(), std::ios::binary); std::istringstream tmp_is(tmp_os.str(), std::ios::binary);
return deSerializeJsonString(tmp_is); return deSerializeJsonString(tmp_is);
} else }
return tmp_os.str();
return tmp_os.str();
} }
//// ////

View File

@ -37,7 +37,7 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#include <endian.h> #include <endian.h>
#endif #endif
#endif #endif
#include <string.h> // for memcpy #include <cstring> // for memcpy
#include <iostream> #include <iostream>
#include <string> #include <string>
#include <vector> #include <vector>

View File

@ -24,10 +24,10 @@ SOFTWARE.
*/ */
#include <stdio.h> #include <cstdio>
#include <string.h> #include <cstring>
#include <stdlib.h> #include <cstdlib>
#include <assert.h> #include <cassert>
#include "sha1.h" #include "sha1.h"
@ -96,7 +96,7 @@ void SHA1::process()
+(bytes[t*4 + 2] << 8) +(bytes[t*4 + 2] << 8)
+ bytes[t*4 + 3]; + bytes[t*4 + 3];
for(; t< 80; t++ ) W[t] = lrot( W[t-3]^W[t-8]^W[t-14]^W[t-16], 1 ); for(; t< 80; t++ ) W[t] = lrot( W[t-3]^W[t-8]^W[t-14]^W[t-16], 1 );
/* main loop */ /* main loop */
Uint32 temp; Uint32 temp;
for( t = 0; t < 80; t++ ) for( t = 0; t < 80; t++ )
@ -154,7 +154,7 @@ void SHA1::addBytes( const char* data, int num )
num -= toCopy; num -= toCopy;
data += toCopy; data += toCopy;
unprocessedBytes += toCopy; unprocessedBytes += toCopy;
// there is a full block // there is a full block
if( unprocessedBytes == 64 ) process(); if( unprocessedBytes == 64 ) process();
} }
@ -168,7 +168,7 @@ unsigned char* SHA1::getDigest()
Uint32 totalBitsH = size >> 29; Uint32 totalBitsH = size >> 29;
// add 0x80 to the message // add 0x80 to the message
addBytes( "\x80", 1 ); addBytes( "\x80", 1 );
unsigned char footer[64] = { 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,
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,

View File

@ -31,13 +31,14 @@
#include <windows.h> #include <windows.h>
#include <wincrypt.h> #include <wincrypt.h>
#else #else
#include <time.h> #include <ctime>
#endif #endif
// clang-format on // clang-format on
#include <stdlib.h> #include <cstdlib>
#include <string.h> #include <cstring>
#include <stdio.h> #include <cstdio>
#include <config.h> #include <config.h>

View File

@ -78,8 +78,8 @@ public:
template<typename Key, typename T, typename Caller, typename CallerData> template<typename Key, typename T, typename Caller, typename CallerData>
class GetRequest { class GetRequest {
public: public:
GetRequest() {} GetRequest() = default;
~GetRequest() {} ~GetRequest() = default;
GetRequest(const Key &a_key): key(a_key) GetRequest(const Key &a_key): key(a_key)
{ {
@ -189,7 +189,7 @@ class UpdateThread : public Thread
{ {
public: public:
UpdateThread(const std::string &name) : Thread(name + "Update") {} UpdateThread(const std::string &name) : Thread(name + "Update") {}
~UpdateThread() {} ~UpdateThread() = default;
void deferUpdate() { m_update_sem.post(); } void deferUpdate() { m_update_sem.post(); }