id
stringlengths
27
29
content
stringlengths
226
3.24k
codereview_new_cpp_data_10004
static void workspace_delete() is inside the workspace. Abort if we really cannot clean up. */ -// unlink_recursive(workspace); free(workspace); } Don't check in dead code, just delete it. static void workspace_delete() is inside the workspace. Abort if we really cannot clean up. */ free(workspace); }
codereview_new_cpp_data_10005
void work_queue_accumulate_task(struct work_queue *q, struct work_queue_task *t) case WORK_QUEUE_RESULT_TASK_MAX_RUN_TIME: case WORK_QUEUE_RESULT_DISK_ALLOC_FULL: case WORK_QUEUE_RESULT_OUTPUT_TRANSFER_ERROR: - if (t->result == WORK_QUEUE_RESULT_SUCCESS) success = 1; - else if (t->result == WORK_QUEUE_RESULT_RESOURCE_EXHAUSTION) success = 0; - else success = -1; if(category_bucketing_accumulate_summary(c, t->resources_measured, q->current_max_worker, t->taskid, success)) { write_transaction_category(q, c); } Add braces to all these ifs. void work_queue_accumulate_task(struct work_queue *q, struct work_queue_task *t) case WORK_QUEUE_RESULT_TASK_MAX_RUN_TIME: case WORK_QUEUE_RESULT_DISK_ALLOC_FULL: case WORK_QUEUE_RESULT_OUTPUT_TRANSFER_ERROR: + if (t->result == WORK_QUEUE_RESULT_SUCCESS) { success = 1; + } + else if (t->result == WORK_QUEUE_RESULT_RESOURCE_EXHAUSTION) { success = 0; + } + else { success = -1; + } if(category_bucketing_accumulate_summary(c, t->resources_measured, q->current_max_worker, t->taskid, success)) { write_transaction_category(q, c); }
codereview_new_cpp_data_10006
void * itable_pop( struct itable *t ) void *value; itable_firstkey(t); - if(itable_nextkey(t, &key, (void*)&value)) { return itable_remove(t,key); } else { return 0; (void **) ? I think compilers may complain otherwise. void * itable_pop( struct itable *t ) void *value; itable_firstkey(t); + if(itable_nextkey(t, &key, (void**)&value)) { return itable_remove(t,key); } else { return 0;
codereview_new_cpp_data_10157
void Kingdom::openOverviewDialog() dst_pt.y = cur_pt.y + 360; fheroes2::Button buttonHeroes( dst_pt.x, dst_pt.y, ICN::OVERVIEW, 0, 1 ); - // We need to additionally render the background between HEROES and TOWSN/CASTLES buttons. dst_pt.y += 42; fheroes2::Copy( fheroes2::AGG::GetICN( ICN::OVERBACK, 0 ), 540, 444, display, dst_pt.x, dst_pt.y, 99, 5 ); ```suggestion // We need to additionally render the background between HEROES and TOWNS/CASTLES buttons. ``` void Kingdom::openOverviewDialog() dst_pt.y = cur_pt.y + 360; fheroes2::Button buttonHeroes( dst_pt.x, dst_pt.y, ICN::OVERVIEW, 0, 1 ); + // We need to additionally render the background between HEROES and TOWNS/CASTLES buttons. dst_pt.y += 42; fheroes2::Copy( fheroes2::AGG::GetICN( ICN::OVERBACK, 0 ), 540, 444, display, dst_pt.x, dst_pt.y, 99, 5 );
codereview_new_cpp_data_10158
StreamBase & operator>>( StreamBase & msg, World & w ) static_assert( LAST_SUPPORTED_FORMAT_VERSION < FORMAT_VERSION_1002_RELEASE, "Remove the logic below." ); if ( Game::GetLoadVersion() < FORMAT_VERSION_1002_RELEASE ) { - uint32_t dummy; msg >> dummy; } msg >> w.map_objects >> w._seed; This will work only if `dummy` is 0 but what if it is not? Should we at least add an assertion? StreamBase & operator>>( StreamBase & msg, World & w ) static_assert( LAST_SUPPORTED_FORMAT_VERSION < FORMAT_VERSION_1002_RELEASE, "Remove the logic below." ); if ( Game::GetLoadVersion() < FORMAT_VERSION_1002_RELEASE ) { + uint32_t dummy = 0xDEADBEEF; msg >> dummy; + + if ( dummy != 0 ) { + DEBUG_LOG( DBG_GAME, DBG_WARN, "Invalid number of MapActions items: " << dummy ) + } } msg >> w.map_objects >> w._seed;
codereview_new_cpp_data_10159
void Interface::GameArea::Redraw( fheroes2::Image & dst, int flag, bool isPuzzle --greenColorSteps; } - // Not all arrows and their shadows fit in 1 tile. We need to consider by 1 tile bigger area to properly render everything. const fheroes2::Rect extendedVisibleRoi{ tileROI.x - 1, tileROI.y - 1, tileROI.width + 2, tileROI.height + 2 }; for ( ; currentStep != path.end(); ++currentStep ) { ```suggestion // Not all arrows and their shadows fit in 1 tile. We need to consider an area of 1 tile bigger to properly render everything. ``` void Interface::GameArea::Redraw( fheroes2::Image & dst, int flag, bool isPuzzle --greenColorSteps; } + // Not all arrows and their shadows fit in 1 tile. We need to consider an area of 1 tile bigger area to properly render everything. const fheroes2::Rect extendedVisibleRoi{ tileROI.x - 1, tileROI.y - 1, tileROI.width + 2, tileROI.height + 2 }; for ( ; currentStep != path.end(); ++currentStep ) {
codereview_new_cpp_data_10160
namespace fheroes2 Copy( in, 0, 0, out, 0, 0, in.width(), in.height() ); } - void Copy( const Image & in, Image & out, int32_t outX, int32_t outY ) - { - Copy( in, 0, 0, out, outX, outY, in.width(), in.height() ); - } - void Copy( const Image & in, int32_t inX, int32_t inY, Image & out, int32_t outX, int32_t outY, int32_t width, int32_t height ) { if ( !Verify( in, inX, inY, out, outX, outY, width, height ) ) { Please remove this new function. I understand the intention of adding it but we should avoid it because the signature of the function is not the same as others. It contains only 1 input image with no coordinates and an output image with coordinates. We should explicitly state either for both or for nobody. namespace fheroes2 Copy( in, 0, 0, out, 0, 0, in.width(), in.height() ); } void Copy( const Image & in, int32_t inX, int32_t inY, Image & out, int32_t outX, int32_t outY, int32_t width, int32_t height ) { if ( !Verify( in, inX, inY, out, outX, outY, width, height ) ) {
codereview_new_cpp_data_10161
namespace std::filesystem::path dir = argPath.parent_path(); if ( dir.empty() ) { - dir = { "." }; } std::error_code ec; :warning: **clang\-diagnostic\-error** :warning: use of overloaded operator `` = `` is ambiguous \(with operand types `` std::filesystem::path `` and `` void ``\) namespace std::filesystem::path dir = argPath.parent_path(); if ( dir.empty() ) { + dir = std::filesystem::path{ "." }; } std::error_code ec;
codereview_new_cpp_data_10162
namespace Dialog display.render(); } - if ( selectedResolution.width > 0 && selectedResolution.height > 0 && selectedResolution.scale > 0 && ( selectedResolution != currentResolution ) ) { display.setResolution( selectedResolution ); #if !defined( MACOS_APP_BUNDLE ) The inner parentheses look redundant here. namespace Dialog display.render(); } + if ( selectedResolution.width > 0 && selectedResolution.height > 0 && selectedResolution.scale > 0 && selectedResolution != currentResolution ) { display.setResolution( selectedResolution ); #if !defined( MACOS_APP_BUNDLE )
codereview_new_cpp_data_10163
fheroes2::Rect Heroes::GetScoutRoi( const bool ignoreDirection /* = false */ ) c } return { heroPosition.x - ( ( direction == Direction::RIGHT ) ? 1 : scoutRange ), heroPosition.y - ( ( direction == Direction::BOTTOM ) ? 1 : scoutRange ), - ( ( direction == Direction::LEFT || direction == Direction::RIGHT ) ? 0 : scoutRange ) + scoutRange + 1, - ( ( direction == Direction::TOP || direction == Direction::BOTTOM ) ? 0 : scoutRange ) + scoutRange + 1 }; } uint32_t Heroes::UpdateMovementPoints( const uint32_t movePoints, const int skill ) const Hmm, suppose that `scoutRange` is 2 and hero is moving to the right: ``` v previous hero position *>** ^ a newly discovered tile 0123 ``` So we need to redraw 4 tiles beginning from tile 0, right? With this logic: ``` return { 1 - 1, ..., 0 + 2 + 1, ... }; ``` So just 3 tiles will be redrawn instead of 4, right? fheroes2::Rect Heroes::GetScoutRoi( const bool ignoreDirection /* = false */ ) c } return { heroPosition.x - ( ( direction == Direction::RIGHT ) ? 1 : scoutRange ), heroPosition.y - ( ( direction == Direction::BOTTOM ) ? 1 : scoutRange ), + ( ( direction == Direction::LEFT || direction == Direction::RIGHT ) ? 1 : scoutRange ) + scoutRange + 1, + ( ( direction == Direction::TOP || direction == Direction::BOTTOM ) ? 1 : scoutRange ) + scoutRange + 1 }; } uint32_t Heroes::UpdateMovementPoints( const uint32_t movePoints, const int skill ) const
codereview_new_cpp_data_10164
bool Heroes::PickupArtifact( const Artifact & art ) } // If there were artifacts assembled we check them for scout area bonus. - if ( !assembledArtifacts.empty() ) { - for ( const ArtifactSetData & assembledArtifact : assembledArtifacts ) { - if ( scout( static_cast<int32_t>( assembledArtifact._assembledArtifactID ) ) ) { - return true; - } } } } This check is not needed as the for-loop will handle it. Please remove it. bool Heroes::PickupArtifact( const Artifact & art ) } // If there were artifacts assembled we check them for scout area bonus. + for ( const ArtifactSetData & assembledArtifact : assembledArtifacts ) { + if ( scout( static_cast<int32_t>( assembledArtifact._assembledArtifactID ) ) ) { + return true; } } }
codereview_new_cpp_data_10165
bool Heroes::Recruit( const int col, const fheroes2::Point & pt ) // Update the set of recruits in the kingdom kingdom.GetRecruits(); - // After recruiting a hero we reveal map and radar image in hero scout area. Scoute( GetIndex() ); - ScoutRadar(); return true; } Hi @Districh-ru what if this hero is not controlled by local human player (for example, this hero is hired by AI)? bool Heroes::Recruit( const int col, const fheroes2::Point & pt ) // Update the set of recruits in the kingdom kingdom.GetRecruits(); + // After recruiting a hero we reveal map in hero scout area. Scoute( GetIndex() ); + if ( isControlHuman() ) { + // And the radar image map for human player. + ScoutRadar(); + } return true; }
codereview_new_cpp_data_10166
int32_t Interface::Basic::GetDimensionDoorDestination( const int32_t from, const const bool isFadingEnabled = ( gameAreaROI.width > TILEWIDTH * distance ) || ( gameAreaROI.height > TILEWIDTH * distance ); const fheroes2::Rect spellROI = [this, from, distance, isHideInterface, &gameAreaROI]() -> fheroes2::Rect { - const fheroes2::Point heroPos( gameArea.GetRelativeTilePosition( Maps::GetPoint( from ) ) ); - const fheroes2::Point heroPosOffset( heroPos.x - TILEWIDTH * ( distance / 2 ), heroPos.y - TILEWIDTH * ( distance / 2 ) ); - const int32_t x = heroPosOffset.x; - const int32_t y = heroPosOffset.y; // We need to add an extra cell since the hero stands exactly in the middle of a cell const int32_t w = std::min( TILEWIDTH * ( distance + 1 ), gameAreaROI.width ); Is there a reason we create identical variables just to use them below? int32_t Interface::Basic::GetDimensionDoorDestination( const int32_t from, const const bool isFadingEnabled = ( gameAreaROI.width > TILEWIDTH * distance ) || ( gameAreaROI.height > TILEWIDTH * distance ); const fheroes2::Rect spellROI = [this, from, distance, isHideInterface, &gameAreaROI]() -> fheroes2::Rect { + const fheroes2::Point heroPos = gameArea.GetRelativeTilePosition( Maps::GetPoint( from ) ); + const int32_t x = heroPos.x - TILEWIDTH * ( distance / 2 ); + const int32_t y = heroPos.y - TILEWIDTH * ( distance / 2 ); // We need to add an extra cell since the hero stands exactly in the middle of a cell const int32_t w = std::min( TILEWIDTH * ( distance + 1 ), gameAreaROI.width );
codereview_new_cpp_data_10167
void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit return; } - const uint32_t spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; - const uint32_t spellDamage = defender->CalculateDamage( spell, spellPoints, hero, 0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage; :warning: **bugprone\-narrowing\-conversions** :warning: narrowing conversion from `` uint32_t `` \(aka `` unsigned int ``\) to signed type `` int `` is implementation\-defined void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit return; } + const int spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; + const uint32_t spellDamage = defender->CalculateDamage( spell, (uint32_t) spellPoints, hero, 0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage;
codereview_new_cpp_data_10168
void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit return; } - const uint32_t spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; - const uint32_t spellDamage = defender->CalculateDamage( spell, spellPoints, hero, 0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage; :warning: **bugprone\-narrowing\-conversions** :warning: narrowing conversion from `` uint32_t `` \(aka `` unsigned int ``\) to signed type `` int `` is implementation\-defined void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit return; } + const int spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; + const uint32_t spellDamage = defender->CalculateDamage( spell, (uint32_t) spellPoints, hero, 0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage;
codereview_new_cpp_data_10169
void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit } const int spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; - const uint32_t spellDamage = defender->CalculateDamage( spell, (uint32_t)spellPoints, hero, 0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage; :warning: **bugprone\-narrowing\-conversions** :warning: narrowing conversion from `` uint32_t `` \(aka `` unsigned int ``\) to signed type `` int `` is implementation\-defined void Battle::PopupDamageInfo::SetSpellAttackInfo( const Cell * cell, const Unit } const int spellPoints = hero ? hero->GetPower() : DEFAULT_SPELL_DURATION; + const uint32_t spellDamage = defender->CalculateDamage( spell, (uint32_t)spellPoints, hero, (uint32_t)0 /* targetInfo damage */, true /* ignore defending hero */ ); _redraw = true; _minDamage = spellDamage;
codereview_new_cpp_data_10170
void LocalEvent::HandleControllerButtonEvent( const SDL_ControllerButtonEvent & } #endif } - else { - if ( button.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER ) { - _controllerPointerSpeed /= CONTROLLER_TRIGGER_CURSOR_SPEEDUP; - } } } Please combine these else and if statements. void LocalEvent::HandleControllerButtonEvent( const SDL_ControllerButtonEvent & } #endif } + else if ( button.button == SDL_CONTROLLER_BUTTON_RIGHTSHOULDER ) { + _controllerPointerSpeed /= CONTROLLER_TRIGGER_CURSOR_SPEEDUP; } }
codereview_new_cpp_data_10171
Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) - return Artifact( Rand( ART_LEVEL_ALL_NORMAL ) ); else if ( 0xA4 == index ) - return Artifact( Rand( ART_ULTIMATE ) ); else if ( 0xA7 == index ) - return Artifact( Rand( ART_LEVEL_TREASURE ) ); else if ( 0xA9 == index ) - return Artifact( Rand( ART_LEVEL_MINOR ) ); else if ( 0xAB == index ) - return Rand( ART_LEVEL_MAJOR ); DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) ) :warning: **modernize\-return\-braced\-init\-list** :warning: avoid repeating the return type from the declaration; use a braced initializer list instead ```suggestion return Artifact( Rand( ART_LEVEL_TREASURE ) }; ``` Artifact Artifact::FromMP2IndexSprite( uint32_t index ) else if ( Settings::Get().isPriceOfLoyaltySupported() && 0xAB < index && 0xCE > index ) return Artifact( ( index - 1 ) / 2 ); else if ( 0xA3 == index ) + return { Rand( ART_LEVEL_ALL_NORMAL ) }; else if ( 0xA4 == index ) + return { Rand( ART_ULTIMATE ) }; else if ( 0xA7 == index ) + return { Rand( ART_LEVEL_TREASURE ) }; else if ( 0xA9 == index ) + return { Rand( ART_LEVEL_MINOR ) }; else if ( 0xAB == index ) + return { ART_LEVEL_MAJOR }; DEBUG_LOG( DBG_GAME, DBG_WARN, "unknown index: " << static_cast<int>( index ) )
codereview_new_cpp_data_10172
void Battle::Interface::RedrawTargetsWithFrameAnimation( const TargetsInfo & tar // For certain spells reflect the spell sprite if the creature is reflected. const bool isReflectICN = ( icn == ICN::SHIELD || icn == ICN::REDDEATH || icn == ICN::MAGIC08 ); - _unitSpellEffectInfos.reserve( targets.size() ); size_t overlaySpriteCount = _unitSpellEffectInfos.size(); for ( const Battle::TargetInfo & target : targets ) { if ( target.defender ) { According to the logic below, there can already be some elements in the `_unitSpellEffectInfos`, right? (BTW, where will they come from there?) If yes, then we should call `_unitSpellEffectInfos.reserve( _unitSpellEffectInfos.size() + targets.size() );` because we need to take into account the already existing elements. void Battle::Interface::RedrawTargetsWithFrameAnimation( const TargetsInfo & tar // For certain spells reflect the spell sprite if the creature is reflected. const bool isReflectICN = ( icn == ICN::SHIELD || icn == ICN::REDDEATH || icn == ICN::MAGIC08 ); size_t overlaySpriteCount = _unitSpellEffectInfos.size(); + _unitSpellEffectInfos.reserve( overlaySpriteCount + targets.size() ); for ( const Battle::TargetInfo & target : targets ) { if ( target.defender ) {
codereview_new_cpp_data_10173
void Battle::Interface::RedrawTargetsWithFrameAnimation( const TargetsInfo & tar } } -void Battle::Interface::RedrawTroopWithFrameAnimation( Unit & unit, int icn, int m82, CreatueSpellAnimation animation ) { LocalEvent & le = LocalEvent::Get(); Hi @Districh-ru I don't know when exactly this type was introduced, but there is definitely a typo: `CreatueSpellAnimation` -> `CreatureSpellAnimation`. Also please rename the first parameter in this method's declaration in the `battle_interface.h`: `b` -> `unit`. void Battle::Interface::RedrawTargetsWithFrameAnimation( const TargetsInfo & tar } } +void Battle::Interface::RedrawTroopWithFrameAnimation( Unit & unit, int icn, int m82, CreatureSpellAnimation animation ) { LocalEvent & le = LocalEvent::Get();
codereview_new_cpp_data_10174
void Heroes::MeetingDialog( Heroes & otherHero ) std::set<ArtifactSetData> assembledArtifacts = bag_artifacts.assembleArtifactSetIfPossible(); std::set<ArtifactSetData> otherHeroAssembledArtifacts = otherHero.bag_artifacts.assembleArtifactSetIfPossible(); assembledArtifacts.merge( otherHeroAssembledArtifacts ); std::for_each( assembledArtifacts.begin(), assembledArtifacts.end(), Dialog::ArtifactSetAssembled ); Funny thing - in C++17 there is an overload for `merge()` that takes the [rvalue reference](https://en.cppreference.com/w/cpp/container/set/merge), but MSVC 2017 has no idea about it :( This might be turned into just ```cpp assembledArtifacts.merge( otherHero.bag_artifacts.assembleArtifactSetIfPossible() ); ``` and this compiles with modern GCC and Clang, but not with MSVC2017, so we are forced to create a temporary variable. void Heroes::MeetingDialog( Heroes & otherHero ) std::set<ArtifactSetData> assembledArtifacts = bag_artifacts.assembleArtifactSetIfPossible(); std::set<ArtifactSetData> otherHeroAssembledArtifacts = otherHero.bag_artifacts.assembleArtifactSetIfPossible(); + // MSVC 2017 fails to use the std::set<...>::merge( std::set<...> && ) overload here, so we have to use a temporary variable assembledArtifacts.merge( otherHeroAssembledArtifacts ); std::for_each( assembledArtifacts.begin(), assembledArtifacts.end(), Dialog::ArtifactSetAssembled );
codereview_new_cpp_data_10175
int32_t AnimationState::getCurrentFrameXOffset() const if ( currentFrame < offset.size() ) { return offset[currentFrame]; } - else { - // If there is no horizontal offset data, return 0 as offset. - return 0; - } } double AnimationState::movementProgress() const :warning: **readability\-else\-after\-return** :warning: do not use `` else `` after `` return `` ```suggestion { ``` int32_t AnimationState::getCurrentFrameXOffset() const if ( currentFrame < offset.size() ) { return offset[currentFrame]; } + + // If there is no horizontal offset data for currentFrame, return 0 as offset. + return 0; } double AnimationState::movementProgress() const
codereview_new_cpp_data_10176
namespace fheroes2 // 'MOVE_MAIN' has 7 frames and we copy only first 6. const int32_t copyFramesNum = 6; // 'MOVE_MAIN' frames starts from the 6th frame in Golem ICN sprites. - const std::_Vector_iterator firstFrameToCopy = _icnVsSprite[id].begin() + 6; _icnVsSprite[id].insert( _icnVsSprite[id].end(), firstFrameToCopy, firstFrameToCopy + copyFramesNum ); for ( int32_t i = 0; i < copyFramesNum; ++i ) { const size_t frameID = golemICNSize + i; :warning: **clang\-diagnostic\-error** :warning: no viable conversion from `` __gnu_cxx::__normal_iterator<fheroes2::Sprite *, std::vector<fheroes2::Sprite>> `` to `` const std::_Bit_iterator `` namespace fheroes2 // 'MOVE_MAIN' has 7 frames and we copy only first 6. const int32_t copyFramesNum = 6; // 'MOVE_MAIN' frames starts from the 6th frame in Golem ICN sprites. + const std::vector<fheroes2::Sprite>::const_iterator firstFrameToCopy = _icnVsSprite[id].begin() + 6; _icnVsSprite[id].insert( _icnVsSprite[id].end(), firstFrameToCopy, firstFrameToCopy + copyFramesNum ); for ( int32_t i = 0; i < copyFramesNum; ++i ) { const size_t frameID = golemICNSize + i;
codereview_new_cpp_data_10177
void StringReplaceWithLowercase( std::string & workString, const char * pattern, return; } - // This function converts all letters in 'patternReplacement' to lowercase before replacing the 'pattern' in 'workString', - // except for the first word in a sentence. for ( size_t position = workString.find( pattern ); position != std::string::npos; position = workString.find( pattern ) ) { // To determine if the end of a sentence was before this word we parse the character before it // for the presence of full stop, question mark, or exclamation mark, skipping whitespace characters. As stated in the last review we don't need this comment here in the tools.cpp file, only in tools.h. void StringReplaceWithLowercase( std::string & workString, const char * pattern, return; } for ( size_t position = workString.find( pattern ); position != std::string::npos; position = workString.find( pattern ) ) { // To determine if the end of a sentence was before this word we parse the character before it // for the presence of full stop, question mark, or exclamation mark, skipping whitespace characters.
codereview_new_cpp_data_10178
std::vector<std::pair<fheroes2::Point, fheroes2::Sprite>> Heroes::getHeroSprites int flagFrameID = sprite_index; if ( !isMoveEnabled() ) { - flagFrameID = isShipMaster() ? 0 : Game::getAdventureMapAnimationIndex(); } fheroes2::Point offset; :warning: **bugprone\-narrowing\-conversions** :warning: narrowing conversion from `` uint32_t `` \(aka `` unsigned int ``\) to signed type `` int `` is implementation\-defined std::vector<std::pair<fheroes2::Point, fheroes2::Sprite>> Heroes::getHeroSprites int flagFrameID = sprite_index; if ( !isMoveEnabled() ) { + flagFrameID = isShipMaster() ? 0 : static_cast<int>( Game::getAdventureMapAnimationIndex() ); } fheroes2::Point offset;
codereview_new_cpp_data_10179
namespace AI if ( Game::validateAnimationDelay( Game::MAPS_DELAY ) ) { // Update Adventure Map objects' animation. Game::updateAdventureMapAnimationIndex(); - - gameArea.SetRedraw(); } basicInterface.Redraw( Interface::REDRAW_GAMEAREA ); This call is redundant IMHO because we are forcibly redrawing the game area three lines below. namespace AI if ( Game::validateAnimationDelay( Game::MAPS_DELAY ) ) { // Update Adventure Map objects' animation. Game::updateAdventureMapAnimationIndex(); } basicInterface.Redraw( Interface::REDRAW_GAMEAREA );
codereview_new_cpp_data_10180
bool Maps::FileInfo::ReadMP2( const std::string & filename ) void Maps::FileInfo::FillUnions( const int side1Colors, const int side2Colors ) { - static_assert( std::is_same_v<decltype( unions ), uint8_t[KINGDOMMAX]>, "The type of the unions[] member has been changed, check the logic below" ); - - assert( side1Colors >= 0 && side1Colors <= std::numeric_limits<uint8_t>::max() ); - assert( side2Colors >= 0 && side2Colors <= std::numeric_limits<uint8_t>::max() ); - for ( uint32_t i = 0; i < KINGDOMMAX; ++i ) { const uint8_t color = ByteToColor( i ); :warning: **bugprone\-narrowing\-conversions** :warning: narrowing conversion from `` uint32_t `` \(aka `` unsigned int ``\) to signed type `` int `` is implementation\-defined bool Maps::FileInfo::ReadMP2( const std::string & filename ) void Maps::FileInfo::FillUnions( const int side1Colors, const int side2Colors ) { for ( uint32_t i = 0; i < KINGDOMMAX; ++i ) { const uint8_t color = ByteToColor( i );
codereview_new_cpp_data_10181
namespace } } DEBUG_LOG( DBG_GAME, DBG_WARN, "the hero to whom the bonus should be applied has not been found" << ", campaign id: " << scenarioInfoId.campaignId << ", scenario id: " << scenarioInfoId.scenarioId ) return nullptr; }; :warning: **bugprone\-lambda\-function\-name** :warning: inside a lambda, `` __FUNCTION__ `` expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly namespace } } +#ifdef WITH_DEBUG DEBUG_LOG( DBG_GAME, DBG_WARN, "the hero to whom the bonus should be applied has not been found" << ", campaign id: " << scenarioInfoId.campaignId << ", scenario id: " << scenarioInfoId.scenarioId ) +#else + (void)scenarioInfoId; +#endif return nullptr; };
codereview_new_cpp_data_10182
namespace } #endif - bool isPolishOrRussianLanguageAndResources() { - return ( fheroes2::getCurrentLanguage() == fheroes2::SupportedLanguage::Polish && fheroes2::getResourceLanguage() == fheroes2::SupportedLanguage::Polish ) - || ( fheroes2::getCurrentLanguage() == fheroes2::SupportedLanguage::Russian && fheroes2::getResourceLanguage() == fheroes2::SupportedLanguage::Russian ); } bool IsValidICNId( int id ) We should name this function more generically like `useOriginalResources`. We should also cache function's return values as they aren't inlined: ```cpp bool useOriginalResources() { const fheroes2::SupportedLanguage currentLanguage = fheroes2::getCurrentLanguage(); const fheroes2::SupportedLanguage resourceLanguage = fheroes2::getResourceLanguage(); return ( currentLanguage == fheroes2::SupportedLanguage::Polish && resourceLanguage == fheroes2::SupportedLanguage::Polish ) || ( currentLanguage == fheroes2::SupportedLanguage::Russian && resourceLanguage == fheroes2::SupportedLanguage::Russian ); } ``` namespace } #endif + bool useOriginalResources() { + const fheroes2::SupportedLanguage currentLanguage = fheroes2::getCurrentLanguage(); + const fheroes2::SupportedLanguage resourceLanguage = fheroes2::getResourceLanguage(); + return ( currentLanguage == fheroes2::SupportedLanguage::Polish && resourceLanguage == fheroes2::SupportedLanguage::Polish ) + || ( currentLanguage == fheroes2::SupportedLanguage::Russian && resourceLanguage == fheroes2::SupportedLanguage::Russian ); } bool IsValidICNId( int id )
codereview_new_cpp_data_10183
namespace AI // The size of heroes can be increased if a new hero is released from Jail. const size_t maxHeroCount = std::max( heroes.size(), availableHeroes.size() ); - const size_t progressValue = ( endProgressValue - startProgressValue ) * ( maxHeroCount - availableHeroes.size() ) / maxHeroCount + startProgressValue; - status.RedrawStatusIfNeeded( static_cast<uint32_t>( progressValue ) ); } const bool allHeroesMoved = availableHeroes.empty(); Hi @ihhub Could there in theory be division by zero if kingdom has no heroes? namespace AI // The size of heroes can be increased if a new hero is released from Jail. const size_t maxHeroCount = std::max( heroes.size(), availableHeroes.size() ); + if ( maxHeroCount > 0 ) { + // At least one hero still exist in the kingdom. + const size_t progressValue = ( endProgressValue - startProgressValue ) * ( maxHeroCount - availableHeroes.size() ) / maxHeroCount + startProgressValue; + + status.RedrawStatusIfNeeded( static_cast<uint32_t>( progressValue ) ); + } } const bool allHeroesMoved = availableHeroes.empty();
codereview_new_cpp_data_10184
void Maps::Tiles::redrawBottomLayerObjects( fheroes2::Image & dst, bool isPuzzle // Some addons must be rendered after the main object on the tile. This applies for flags. // Since this method is called intensively during rendering we have to avoid memory allocation on heap. const size_t maxPostRenderAddons = 16; - std::array<const TilesAddon *, maxPostRenderAddons> postRenderingAddon{ nullptr }; size_t postRenderAddonCount = 0; for ( const TilesAddon & addon : addons_level1 ) { I believe we can avoid its initialization at all and conserve one `REP STOSB` ;) Or, if you still prefer to initialize it, we can just use the [zero-initialization](https://en.cppreference.com/w/cpp/language/zero_initialization) and replace `{ nullptr }` with just `{}`. void Maps::Tiles::redrawBottomLayerObjects( fheroes2::Image & dst, bool isPuzzle // Some addons must be rendered after the main object on the tile. This applies for flags. // Since this method is called intensively during rendering we have to avoid memory allocation on heap. const size_t maxPostRenderAddons = 16; + std::array<const TilesAddon *, maxPostRenderAddons> postRenderingAddon{}; size_t postRenderAddonCount = 0; for ( const TilesAddon & addon : addons_level1 ) {
codereview_new_cpp_data_10185
void Battle::Arena::SetCastleTargetValue( int target, uint32_t value ) case CAT_BRIDGE: if ( _bridge->isValid() ) { - if ( !_bridge->isDown() ) { - _bridge->SetDown( true ); - } - _bridge->SetDestroy(); } break; We aren't showing bridge animation anymore. @Branikolog , what do you think about this? void Battle::Arena::SetCastleTargetValue( int target, uint32_t value ) case CAT_BRIDGE: if ( _bridge->isValid() ) { + _bridge->SetDown( true ); _bridge->SetDestroy(); } break;
codereview_new_cpp_data_10186
Troops::Troops( const Troops & troops ) : std::vector<Troop *>() { reserve( troops.size() ); - for ( const_iterator it = troops.begin(); it != troops.end(); ++it ) - push_back( new Troop( **it ) ); } Troops::~Troops() :warning: **modernize\-loop\-convert** :warning: use range\-based for loop instead ```suggestion for (auto troop : troops) ``` Troops::Troops( const Troops & troops ) : std::vector<Troop *>() { reserve( troops.size() ); + for ( const auto & troop : troops ) { + push_back( new Troop( *troop ) ); + } } Troops::~Troops()
codereview_new_cpp_data_10187
namespace AI } } - // Call internally checks if it's valid (space/resources) to buy one. const Kingdom & kingdom = castle.GetKingdom(); if ( !kingdom.GetHeroes().empty() && kingdom.GetFunds() >= PaymentConditions::BuyBoat() * ( islandOrPeninsula ? 2 : 4 ) ) { castle.BuyBoat(); Could you please elaborate, which call checks what? The current wording gives the impression that `GetKingdom()` does this. namespace AI } } + // Check if the kingdom has at least one hero and enough resources to buy a boat. const Kingdom & kingdom = castle.GetKingdom(); if ( !kingdom.GetHeroes().empty() && kingdom.GetFunds() >= PaymentConditions::BuyBoat() * ( islandOrPeninsula ? 2 : 4 ) ) { castle.BuyBoat();
codereview_new_cpp_data_10188
namespace const uint8_t * dataEnd = data + size; while ( data != dataEnd ) { if ( *data == lineSeparator || isSpaceChar( *data ) ) { - // If it is the end of line ("\n") or a space (""), then the word has ended. if ( maxWidth < width ) { maxWidth = width; } A tiny comment correction: `space ("")` should be `space (" ")` with a space :) namespace const uint8_t * dataEnd = data + size; while ( data != dataEnd ) { if ( *data == lineSeparator || isSpaceChar( *data ) ) { + // If it is the end of line ("\n") or a space (" "), then the word has ended. if ( maxWidth < width ) { maxWidth = width; }
codereview_new_cpp_data_10189
namespace ERROR_LOG( "Failed to set a linear scale hint for rendering." ) } - // Setting this hint prevents the window to regain focus after loosing it in fullscreen mode. // It also fixes issues when SDL_UpdateTexture() calls fail because of refocusing. if ( SDL_SetHint( SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0" ) == SDL_FALSE ) { ERROR_LOG( "Failed to set a linear scale hint for rendering." ) ```suggestion // Setting this hint prevents the window to regain focus after losing it in fullscreen mode. ``` namespace ERROR_LOG( "Failed to set a linear scale hint for rendering." ) } + // Setting this hint prevents the window to regain focus after losing it in fullscreen mode. // It also fixes issues when SDL_UpdateTexture() calls fail because of refocusing. if ( SDL_SetHint( SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0" ) == SDL_FALSE ) { ERROR_LOG( "Failed to set a linear scale hint for rendering." )
codereview_new_cpp_data_10190
Battle::Result Battle::Loader( Army & army1, Army & army2, int32_t mapsindex ) } } bool isBattleOver = false; while ( !isBattleOver ) { - const uint32_t battleSeed = computeBattleSeed( mapsindex, world.GetMapSeed(), army1, army2 ); Rand::DeterministicRandomGenerator randomGenerator( battleSeed ); Arena arena( army1, army2, mapsindex, showBattle, randomGenerator ); Hi @ihhub there is really no need to re-compute the battle seed both for instant battle and manual battle, because none of the `computeBattleSeed()`'s arguments are changed. We can move it out of this loop, just like the `battleSeed` was computed before. Battle::Result Battle::Loader( Army & army1, Army & army2, int32_t mapsindex ) } } + const uint32_t battleSeed = computeBattleSeed( mapsindex, world.GetMapSeed(), army1, army2 ); + bool isBattleOver = false; while ( !isBattleOver ) { Rand::DeterministicRandomGenerator randomGenerator( battleSeed ); Arena arena( army1, army2, mapsindex, showBattle, randomGenerator );
codereview_new_cpp_data_10191
namespace int32_t offsetY = textInitialOffsetY; - TextBox title( _( "Support us at ), Font::BIG, textWidth ); TextBox name( _( "local-donation-platform|https://www.patreon.com/fheroes2" ), Font::YELLOW_BIG, textWidth ); title.Blit( ( textInitialOffsetX - title.w() ) / 2, offsetY, output ); name.Blit( ( textInitialOffsetX - name.w() ) / 2, offsetY + title.h(), output ); :warning: **clang\-diagnostic\-invalid\-pp\-token** :warning: missing terminating `` " `` character namespace int32_t offsetY = textInitialOffsetY; + TextBox title( _( "Support us at" ), Font::BIG, textWidth ); TextBox name( _( "local-donation-platform|https://www.patreon.com/fheroes2" ), Font::YELLOW_BIG, textWidth ); title.Blit( ( textInitialOffsetX - title.w() ) / 2, offsetY, output ); name.Blit( ( textInitialOffsetX - name.w() ) / 2, offsetY + title.h(), output );
codereview_new_cpp_data_10192
void Heroes::PortraitRedraw( const int32_t px, const int32_t py, const PortraitT } } - if ( ( GetControl() & CONTROL_AI ) != 0 ) { // AI heroes should not have any UI indicators for their statuses. return; } There should be also `isControlAI()`, which is a bit shorter, but is effectively the same. void Heroes::PortraitRedraw( const int32_t px, const int32_t py, const PortraitT } } + if ( isControlAI() ) { // AI heroes should not have any UI indicators for their statuses. return; }
codereview_new_cpp_data_10193
namespace std::vector<fheroes2::SupportedLanguage> temp = languages; items.SetListContent( temp ); - const fheroes2::Size currentResolution( display.width(), display.height() ); - - fheroes2::Size selectedResolution; for ( size_t i = 0; i < languages.size(); ++i ) { if ( languages[i] == chosenLanguage ) { items.SetCurrent( i ); What is the purpose of this variable? namespace std::vector<fheroes2::SupportedLanguage> temp = languages; items.SetListContent( temp ); for ( size_t i = 0; i < languages.size(); ++i ) { if ( languages[i] == chosenLanguage ) { items.SetCurrent( i );
codereview_new_cpp_data_10194
namespace fheroes2 icnVsSprite[75].setPosition( icnVsSprite[75].x(), icnVsSprite[75].y() ); updateSmallFontLetterShadow( icnVsSprite[75] ); } - return; } } :warning: **readability\-redundant\-control\-flow** :warning: redundant return statement at the end of a function with a void return type ```suggestion r ``` namespace fheroes2 icnVsSprite[75].setPosition( icnVsSprite[75].x(), icnVsSprite[75].y() ); updateSmallFontLetterShadow( icnVsSprite[75] ); } } }
codereview_new_cpp_data_10195
namespace #if defined( ANDROID ) // Same as ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE - SDL_SetHint( SDL_HINT_ORIENTATIONS, "LandscapeLeft LandscapeRight" ); #endif uint32_t flags = SDL_WINDOW_SHOWN; This is a "good enough" place for this hint but we should add error check: ```cpp if ( SDL_SetHint( SDL_HINT_ORIENTATIONS, "LandscapeLeft LandscapeRight" ) == SDL_FALSE ) { ERROR_LOG( "Failed to set a landscape orientations." ) } ``` namespace #if defined( ANDROID ) // Same as ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE + if ( SDL_SetHint( SDL_HINT_ORIENTATIONS, "LandscapeLeft LandscapeRight" ) == SDL_FALSE ) { + ERROR_LOG( "Failed to set a hint for screen orientation." ) + } #endif uint32_t flags = SDL_WINDOW_SHOWN;
codereview_new_cpp_data_10264
static bool elektraCheckForInvalidMetaKey (Key * parentKey, KeySet * ks) const KeySet * metaKeys = keyMeta (cur); for (elektraCursor jt = 0; jt < ksGetSize (metaKeys); ++jt) { - // We reach her iff we try to set a metakey. Therefore we should t const Key * meta = ksAtCursor (metaKeys, jt); const char * pos = (const char *) keyName (meta); if (elektraStrNCmp (pos, "meta:/internal/mini", 19) != 0 && elektraStrCmp (pos, "meta:/origname") && elektraStrNCmp (pos, "meta:/rename", 12) != 0 && elektraStrCmp (pos, "meta:/binary") != 0) { - ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "The mini storage Plugin doesn't support the met key %s", pos); return false; } } Why are these keys OK? Maybe add a comment explaining? static bool elektraCheckForInvalidMetaKey (Key * parentKey, KeySet * ks) const KeySet * metaKeys = keyMeta (cur); for (elektraCursor jt = 0; jt < ksGetSize (metaKeys); ++jt) { + // Check if the supported metakey is valid + // Rename and origname are used by the rename filter plugin + // Binary is needed for the base64 filter plugin + // Internal is needed for some checker plugins const Key * meta = ksAtCursor (metaKeys, jt); const char * pos = (const char *) keyName (meta); if (elektraStrNCmp (pos, "meta:/internal/mini", 19) != 0 && elektraStrCmp (pos, "meta:/origname") && elektraStrNCmp (pos, "meta:/rename", 12) != 0 && elektraStrCmp (pos, "meta:/binary") != 0) { + ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "The mini storage Plugin doesn't support the meta key %s", pos); return false; } }
codereview_new_cpp_data_10331
static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { // New PyCFunction will own method reference PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); Py_DECREF(method); // __Pyx_PyObject_GetAttrStr - if (unlikely(!unbound_method)) { - return -1; - } target->method = unbound_method; } } ```suggestion if (unlikely(!unbound_method)) return -1; ``` static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) { // New PyCFunction will own method reference PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method); Py_DECREF(method); // __Pyx_PyObject_GetAttrStr + if (unlikely(!unbound_method)) return -1; target->method = unbound_method; } }
codereview_new_cpp_data_10332
typedef struct { /////////////// UnpackUnboundCMethod /////////////// //@requires: PyObjectGetAttrStr -#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) -#define __PYX_REINTERPRET_POINTER(pointer_type, pointer) ((pointer_type)(void *)(pointer)) -#define __PYX_RUNTIME_REINTERPRET(type, var) (*(type *)(&var)) - static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); if (unlikely(!selfless_args)) return NULL; Do I need to use cython versions of those (`PyTuple_GetSlice`, `PyTuple_Size`), if they exist (I didn't really check)? typedef struct { /////////////// UnpackUnboundCMethod /////////////// //@requires: PyObjectGetAttrStr static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + // NOTE: possible optimization - use vectorcall PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); if (unlikely(!selfless_args)) return NULL;
codereview_new_cpp_data_10333
typedef struct { /////////////// UnpackUnboundCMethod /////////////// //@requires: PyObjectGetAttrStr -#define __PYX_REINTERPRET_FUNCION(func_pointer, other_pointer) ((func_pointer)(void(*)(void))(other_pointer)) -#define __PYX_REINTERPRET_POINTER(pointer_type, pointer) ((pointer_type)(void *)(pointer)) -#define __PYX_RUNTIME_REINTERPRET(type, var) (*(type *)(&var)) - static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); if (unlikely(!selfless_args)) return NULL; You seem to be using only the first of these three. We shouldn't commit unused code. It's really nice to know about these, though. We could add them to `ModuleSetupCode.c` instead and comment them out with `//`, so that the unused ones don't take any space in the generated C files, but are still available if they start becoming useful. (There are probably places already where they could be applied.) typedef struct { /////////////// UnpackUnboundCMethod /////////////// //@requires: PyObjectGetAttrStr static PyObject *__Pyx_SelflessCall(PyObject *method, PyObject *args, PyObject *kwargs) { + // NOTE: possible optimization - use vectorcall PyObject *selfless_args = PyTuple_GetSlice(args, 1, PyTuple_Size(args)); if (unlikely(!selfless_args)) return NULL;
codereview_new_cpp_data_10335
#undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC - #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_NUM >= 0x07030900) #endif #elif defined(CYTHON_LIMITED_API) Did this creep in from #5074, or is it on purpose? #undef CYTHON_USE_EXC_INFO_STACK #define CYTHON_USE_EXC_INFO_STACK 0 #ifndef CYTHON_UPDATE_DESCRIPTOR_DOC + #define CYTHON_UPDATE_DESCRIPTOR_DOC (PYPY_VERSION_HEX >= 0x07030900) #endif #elif defined(CYTHON_LIMITED_API)
codereview_new_cpp_data_10341
typedef struct { #ifdef __PYX_DEBUG_ATOMICS #warning "Using GNU atomics" #endif -#elif CYTHON_ATOMICS && defined(_MSC_VER) /* msvc */ #include <intrin.h> #undef __pyx_atomic_int_type If we wanted to make this less liable to break the rest of the world then we could only enable Windows atomics in the Nogil branch for now? ``` #elif CYTHON_ATOMICS && defined(_MSC_VER) && CYTHON_COMPILING_IN_NOGIL ``` No sure if that's a good idea or not, but it makes it a less drastic change typedef struct { #ifdef __PYX_DEBUG_ATOMICS #warning "Using GNU atomics" #endif +#elif CYTHON_ATOMICS && defined(_MSC_VER) && CYTHON_COMPILING_IN_NOGIL /* msvc */ #include <intrin.h> #undef __pyx_atomic_int_type
codereview_new_cpp_data_10344
class __Pyx_FakeReference { #endif #define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) -#ifndef CO_GENERATOR - #define CO_GENERATOR 0x20 -#endif #ifndef CO_COROUTINE #define CO_COROUTINE 0x80 #endif I checked, this was already added in Python 2.2, when generators were introduced. No need to assume it could be undefined. ```suggestion ``` class __Pyx_FakeReference { #endif #define __Pyx_NoneAsNull(obj) (__Pyx_Py_IsNone(obj) ? NULL : (obj)) #ifndef CO_COROUTINE #define CO_COROUTINE 0x80 #endif
codereview_new_cpp_data_10350
namespace machine_learning { /** * @namespace k_nearest_neighbors - * @brief K-nearest neighbors algorithm */ namespace k_nearest_neighbors { ```suggestion * @brief Functions for the [K-Nearest Neighbors algorithm] * (https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm) implementation ``` namespace machine_learning { /** * @namespace k_nearest_neighbors + * @brief Functions for the [K-Nearest Neighbors algorithm] + * (https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm) implementation */ namespace k_nearest_neighbors {
codereview_new_cpp_data_10351
* Geeks For Geeks link [https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/] */ -#include <cassert> -#include <iostream> using namespace std; int maxCircularSum(int a[], int n) Please add a one-line description of what the library/header is for (**see the example below**). ```c++ #include <iostream> /// for IO operations #include <cassert> /// for assert ``` * Geeks For Geeks link [https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/] */ +#include <cassert> /// for assert +#include <iostream> /// for IO stream using namespace std; int maxCircularSum(int a[], int n)
codereview_new_cpp_data_10352
* @details * The idea is to modify Kadane’s algorithm to find a minimum contiguous subarray sum and the maximum contiguous subarray sum, * then check for the maximum value between the max_value and the value left after subtracting min_value from the total sum. -* [Geeks For Geeks](https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/) */ #include <cassert> /// for assert ```suggestion * For more information, check [Geeks For Geeks](https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/) explanation page. ``` * @details * The idea is to modify Kadane’s algorithm to find a minimum contiguous subarray sum and the maximum contiguous subarray sum, * then check for the maximum value between the max_value and the value left after subtracting min_value from the total sum. +* For more information, check [Geeks For Geeks](https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/) explanation page. */ #include <cassert> /// for assert
codereview_new_cpp_data_10353
* @author [KillerAV] (https://github.com/KillerAV) */ -#include <cassert> // for std::assert -#include <iostream> // for io operations -#include <vector> // for vector -#include <unordered_map> // for unordered map /** * @namespace dynamic_programming ```suggestion #include <cassert> /// for std::assert #include <iostream> /// for IO operations #include <vector> /// for std::vector #include <unordered_map> /// for unordered map ``` * @author [KillerAV] (https://github.com/KillerAV) */ +#include <cassert> /// for std::assert +#include <iostream> /// for IO operations +#include <vector> /// for std::vector +#include <unordered_map> /// for unordered map /** * @namespace dynamic_programming
codereview_new_cpp_data_10354
* the array. For example, array = [1, -10, 2, 31, -6], targetSum = -14. * Output: true => We can pick subset [-10, 2, -6] with sum as * (-10) + 2 + (-6) = -14. - * @author [KillerAV] (https://github.com/KillerAV) */ #include <cassert> /// for std::assert ```suggestion * @author [KillerAV](https://github.com/KillerAV) ``` * the array. For example, array = [1, -10, 2, 31, -6], targetSum = -14. * Output: true => We can pick subset [-10, 2, -6] with sum as * (-10) + 2 + (-6) = -14. + * @author [KillerAV](https://github.com/KillerAV) */ #include <cassert> /// for std::assert
codereview_new_cpp_data_10355
int main() std::cout << "Size can only be 1-30. Please choose another value: "; std::cin >> size; } - } int *array = new int[size]; int key = 0; This seems to be causing the CI to fail. ```suggestion ``` int main() std::cout << "Size can only be 1-30. Please choose another value: "; std::cin >> size; } int *array = new int[size]; int key = 0;
codereview_new_cpp_data_10356
struct ListNode { ListNode(int x, ListNode *next) : val(x), next(next) {} // Constructor with values provided for node->val and node->next }; - #include <iostream> // for IO operations - #include <cassert> // for assert in tests /** * @namespace search I suggest moving these before declaring any functions/variables. ```suggestion #include <iostream> /// for IO operations #include <cassert> /// for assert ``` __ [![sema-logo](https://app.semasoftware.com/img/sema-tray-logo.gif)](https://semasoftware.com/gh) &nbsp;**Summary:** :hammer_and_wrench: This code needs a fix&nbsp; | &nbsp;**Tags:** Inefficient struct ListNode { ListNode(int x, ListNode *next) : val(x), next(next) {} // Constructor with values provided for node->val and node->next }; + #include <iostream> /// for IO operations + #include <cassert> /// for assert /** * @namespace search
codereview_new_cpp_data_10357
* @file * @brief Given a linked list L[0,....,n] of n numbers, find the middle node. * - * @details The technique utilized in this implementation is the "Floyd's tortise and hare" approach. Wikipedia link to technique: https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare * This technique uses two pointers that iterate through the list at different 'speeds' in order to solve problems. * In this implementation, for every iteration the slow pointer advances one node while the fast pointer advances two nodes. * The result of this is that since the fast pointer moves twice as fast as the slow pointer, when the fast pointer reaches the end of the list ```suggestion * @details The technique utilized in this implementation is the ["Floyd's tortoise and hare"](https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare) approach. ``` __ [![sema-logo](https://app.semasoftware.com/img/sema-tray-logo.gif)](https://semasoftware.com/gh) &nbsp;**Summary:** :hammer_and_wrench: This code needs a fix&nbsp; | &nbsp;**Tags:** Inelegant * @file * @brief Given a linked list L[0,....,n] of n numbers, find the middle node. * + * @details The technique utilized in this implementation is the ["Floyd's tortoise and hare"](https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_tortoise_and_hare) approach. * This technique uses two pointers that iterate through the list at different 'speeds' in order to solve problems. * In this implementation, for every iteration the slow pointer advances one node while the fast pointer advances two nodes. * The result of this is that since the fast pointer moves twice as fast as the slow pointer, when the fast pointer reaches the end of the list
codereview_new_cpp_data_10358
#include <iostream> #include <vector> #include <cassert> -#include <limits.h> /** * @namespace graph ```suggestion #include <climits> ``` __ [![sema-logo](https://app.semasoftware.com/img/sema-tray-logo.gif)](https://semasoftware.com/gh) &nbsp;**Summary:** :hammer_and_wrench: This code needs a fix&nbsp; | &nbsp;**Tags:** Not secure #include <iostream> #include <vector> #include <cassert> +#include <climits> /** * @namespace graph
codereview_new_cpp_data_10359
#include <iostream> #include <vector> #include <cassert> -#include <limits.h> /** * @namespace graph Please add a one-line description of what the library/header is for (**see the example below**). ```c++ #include <iostream> /// for IO operations #include <cassert> /// for assert ``` __ [![sema-logo](https://app.semasoftware.com/img/sema-tray-logo.gif)](https://semasoftware.com/gh) &nbsp;**Summary:** :hammer_and_wrench: This code needs a fix&nbsp; | &nbsp;**Tags:** Inefficient #include <iostream> #include <vector> #include <cassert> +#include <climits> /** * @namespace graph
codereview_new_cpp_data_10360
namespace list_array { /** * @brief Structure of List with supporting methods. */ - template <int N> struct list { std::array<uint64_t, N> data{}; // Array that implement list uint64_t top = 0; // Pointer to the last element I believe we should use `uint64_t` in here like the other values. ```suggestion template <uint64_t N> ``` __ [![sema-logo](https://app.semasoftware.com/img/sema-tray-logo.gif)](https://semasoftware.com/gh) &nbsp;**Summary:** :hammer_and_wrench: This code needs a fix&nbsp; | &nbsp;**Tags:** Not maintainable namespace list_array { /** * @brief Structure of List with supporting methods. */ + template <uint64_t N> struct list { std::array<uint64_t, N> data{}; // Array that implement list uint64_t top = 0; // Pointer to the last element
codereview_new_cpp_data_10361
std::size_t hashInt_2(int x) { y = y ^ (y >> 31); return y; } -} // namespace data_structures /** * @brief Test for bloom filter with string as generic type ```suggestion } // namespace data_structures ``` __ [![sema-logo](https://app.semasoftware.com/img/sema-tray-logo.gif)](https://semasoftware.com/gh) &nbsp;**Tags:** Inefficient std::size_t hashInt_2(int x) { y = y ^ (y >> 31); return y; } +} // namespace data_structures /** * @brief Test for bloom filter with string as generic type
codereview_new_cpp_data_10362
struct CheckWeightsFunctor : DefaultErrorReporter // Get weights matrix and gradient const auto& weights_matrix = dtw.get_values(); const auto& gradient = dtw.get_optimizer()->get_gradient(); - // std::cout << "*** CHECKING WEIGHTS: NAME=" << dtw.get_name() << ", SIZE=" - // << weights_matrix.Height() << "x" << weights_matrix.Width() << std::endl; // Iterate through weights matrix entries for (El::Int col = 0; col < weights_matrix.Width(); ++col) { for (El::Int row = 0; row < weights_matrix.Height(); ++row) { - // std::cout << "*** CHECKING WEIGHTS (name=" << dtw.get_name() << "): - // row=" << row << ", col=" << col << std::endl; const bool weight_is_local = weights_matrix.IsLocal(row, col); const El::Int local_row = (weight_is_local ? weights_matrix.LocalRow(row) Eventually this debug code should be removed. struct CheckWeightsFunctor : DefaultErrorReporter // Get weights matrix and gradient const auto& weights_matrix = dtw.get_values(); const auto& gradient = dtw.get_optimizer()->get_gradient(); // Iterate through weights matrix entries for (El::Int col = 0; col < weights_matrix.Width(); ++col) { for (El::Int row = 0; row < weights_matrix.Height(); ++row) { const bool weight_is_local = weights_matrix.IsLocal(row, col); const El::Int local_row = (weight_is_local ? weights_matrix.LocalRow(row)
codereview_new_cpp_data_10365
TEST(get_or) { CHECK_EQUAL(foo, "bar"); auto bar = get_or(x, "bar", fallback); CHECK_EQUAL(bar, "fallback"); } Can you also add a test for get_or with a fallback string literal? I think there's a missing overload. TEST(get_or) { CHECK_EQUAL(foo, "bar"); auto bar = get_or(x, "bar", fallback); CHECK_EQUAL(bar, "fallback"); + auto qux = get_or(x, "qux", "literal"); + CHECK_EQUAL(qux, "literal"); }
codereview_new_cpp_data_10366
expression expand_extractor(predicate::operand operand) { auto make_field_char_parser() { using parsers::chr; return parsers::alnum | chr{'_'} | chr{'-'} | chr{':'}; } I find it strange that this is out of sync with the `field_name` from the `legacy_type` parser: ``` auto field_name = parsers::identifier | parsers::qqstr; ``` The identifier parser is defined standalone as: ``` constexpr inline auto identifier_char = (alnum | ch<'_'> | ch<'.'>); constexpr inline auto identifier = +identifier_char; ``` It would be great to turn this into a hierarchy that builds on shared blocks. Alternatively the relationship needs to be documented in both places. expression expand_extractor(predicate::operand operand) { auto make_field_char_parser() { using parsers::chr; + // TODO: Align this with identifier_char. return parsers::alnum | chr{'_'} | chr{'-'} | chr{':'}; }
codereview_new_cpp_data_10367
struct accountant_state_impl { /// Stores the names of known actors to fill into the actor_name column. std::unordered_map<caf::actor_id, std::string> actor_map; - /// Stores the builder instance. std::unordered_map<std::string, table_slice_builder_ptr> builders; /// Buffers table_slices, acting as a adaptor between the push based ```suggestion /// Stores the builder instance per type name. ``` struct accountant_state_impl { /// Stores the names of known actors to fill into the actor_name column. std::unordered_map<caf::actor_id, std::string> actor_map; + /// Stores the builder instance per type name. std::unordered_map<std::string, table_slice_builder_ptr> builders; /// Buffers table_slices, acting as a adaptor between the push based
codereview_new_cpp_data_10368
TEST(evaluation - pattern matching) { evaluate(unbox(to<pattern>("/f.*o/")), relational_operator::equal, "foo")); CHECK( evaluate("foo", relational_operator::equal, unbox(to<pattern>("/f.*o/")))); } TEST(serialization) { Can we also test case-insensitive evaluation? TEST(evaluation - pattern matching) { evaluate(unbox(to<pattern>("/f.*o/")), relational_operator::equal, "foo")); CHECK( evaluate("foo", relational_operator::equal, unbox(to<pattern>("/f.*o/")))); + CHECK( + evaluate(unbox(to<pattern>("/f.*o/i")), relational_operator::equal, "FOO")); + CHECK( + evaluate("FOO", relational_operator::equal, unbox(to<pattern>("/f.*o/i")))); } TEST(serialization) {
codereview_new_cpp_data_10369
auto server_command(const vast::invocation& inv, caf::actor_system& system) setup_cors_preflight_handlers(router, *server_config->cors_allowed_origin); // Set up non-API routes. router->non_matched_request_handler([](auto req) { - VAST_VERBOSE("404 not found: {} {}", req->header().method(), req->header().path()); return req->create_response(restinio::status_not_found()) .set_body("404 not found\n") The method here is not formattable. auto server_command(const vast::invocation& inv, caf::actor_system& system) setup_cors_preflight_handlers(router, *server_config->cors_allowed_origin); // Set up non-API routes. router->non_matched_request_handler([](auto req) { + VAST_VERBOSE("404 not found: {} {}", req->header().method().c_str(), req->header().path()); return req->create_response(restinio::status_not_found()) .set_body("404 not found\n")
codereview_new_cpp_data_10370
parse_arguments(const std::vector<std::string>& args) { }; } const auto repr = detail::join(args.begin(), args.end(), " "); - using parsers::space, parsers::expr, parsers::eoi; auto f = repr.begin(); const auto l = repr.end(); auto parsed_expr = expression{}; - const auto optional_ws = ignore(*space); bool has_expr = true; if (!expr(f, l, parsed_expr)) { VAST_DEBUG("failed to parse expr from '{}'", repr); Should we use blank over space here? parse_arguments(const std::vector<std::string>& args) { }; } const auto repr = detail::join(args.begin(), args.end(), " "); + using parsers::blank, parsers::expr, parsers::eoi; auto f = repr.begin(); const auto l = repr.end(); auto parsed_expr = expression{}; + const auto optional_ws = ignore(*blank); bool has_expr = true; if (!expr(f, l, parsed_expr)) { VAST_DEBUG("failed to parse expr from '{}'", repr);
codereview_new_cpp_data_10371
caf::error ip_index::unpack_impl(const fbs::ValueIndex& from) { if (from_ip->byte_indexes()->size() != bytes_.size()) return caf::make_error(ec::format_error, fmt::format("unexpected number of byte indexes in " - "ip index: expected {}, got {}", bytes_.size(), from_ip->byte_indexes()->size())); for (size_t i = 0; i < bytes_.size(); ++i) ```suggestion "IP index: expected {}, got {}", ``` caf::error ip_index::unpack_impl(const fbs::ValueIndex& from) { if (from_ip->byte_indexes()->size() != bytes_.size()) return caf::make_error(ec::format_error, fmt::format("unexpected number of byte indexes in " + "IP index: expected {}, got {}", bytes_.size(), from_ip->byte_indexes()->size())); for (size_t i = 0; i < bytes_.size(); ++i)
codereview_new_cpp_data_10372
caf::behavior pivoter(caf::stateful_actor<pivoter_state>* self, node_actor node, auto normalized_expr = normalize_and_validate(std::move(expr)); if (!normalized_expr) { self->quit(caf::make_error(ec::format_error, - fmt::format("pivoter failed to normalize and " "validate expression: {}", - normalized_expr.error()))); return {}; } expr = *normalized_expr; Generally you can replace the actor name with `{}` and then provide `*self` to the formatter to avoid the duplication. This also applies to the other two instances of this. caf::behavior pivoter(caf::stateful_actor<pivoter_state>* self, node_actor node, auto normalized_expr = normalize_and_validate(std::move(expr)); if (!normalized_expr) { self->quit(caf::make_error(ec::format_error, + fmt::format("{} failed to normalize and " "validate expression: {}", + *self, normalized_expr.error()))); return {}; } expr = *normalized_expr;
codereview_new_cpp_data_10373
TEST(No dense indexes serialization when create dense index in config is false) last_written_chunks; auto filesystem = sys.spawn(dummy_filesystem, std::ref(last_written_chunks)); const auto partition_id = vast::uuid::random(); - // FIXME: We should implement a mock store and use that for this test. const auto* store_plugin = vast::plugins::find<vast::store_actor_plugin>( vast::defaults::system::store_backend); REQUIRE(store_plugin); Wouldn't it already suffice to use the default store with the memory filesystem here? Regardless, do you still want to fix this within this PR? Otherwise `s/FIXME/TODO`. TEST(No dense indexes serialization when create dense index in config is false) last_written_chunks; auto filesystem = sys.spawn(dummy_filesystem, std::ref(last_written_chunks)); const auto partition_id = vast::uuid::random(); + // TODO: We should implement a mock store and use that for this test. const auto* store_plugin = vast::plugins::find<vast::store_actor_plugin>( vast::defaults::system::store_backend); REQUIRE(store_plugin);
codereview_new_cpp_data_10374
class example_plugin final : public virtual analyzer_plugin, } /// Returns the unique name of the plugin. - std::string_view name() const override { return "example-analyzer"; } Shouldn't these simply return a `std::string`? class example_plugin final : public virtual analyzer_plugin, } /// Returns the unique name of the plugin. + std::string name() const override { return "example-analyzer"; }
codereview_new_cpp_data_10375
class writer : public format::writer { auto&& layout = slice.layout(); // TODO: relax this check. We really only need the (1) flow, and (2) PCAP // payload. Everything else is optional. - if (!congruent(layout, make_packet_type())) { return caf::make_error( ec::format_error, fmt::format("pcap-writer is unable to write batch " "of schema '{}': expected 'pcap.packet'", I would do this not via congruency, now that the writer gets everything. Two approaches come to mind: 1. Just look at the schema name and bail out if it's not `pcap.packet` 2. Ensure that the blob payload has the right attribute value, e.g., `libpcap-packet`, to ensure that you can stuff it into the libpcap function without producing garbage class writer : public format::writer { auto&& layout = slice.layout(); // TODO: relax this check. We really only need the (1) flow, and (2) PCAP // payload. Everything else is optional. + if (layout.name() != "pcap.packet" + || !congruent(layout, make_packet_type())) { return caf::make_error( ec::format_error, fmt::format("pcap-writer is unable to write batch " "of schema '{}': expected 'pcap.packet'",
codereview_new_cpp_data_10376
namespace vast { namespace { inline uint32_t bitmask32(size_t bottom_bits) { return bottom_bits >= 32 ? 0xffffffff : ((uint32_t{1} << bottom_bits) - 1); } Please use snake_case in the code base for consistency. namespace vast { namespace { + inline uint32_t bitmask32(size_t bottom_bits) { return bottom_bits >= 32 ? 0xffffffff : ((uint32_t{1} << bottom_bits) - 1); }
codereview_new_cpp_data_10377
export_helper(export_helper_actor::stateful_pointer<export_helper_state> self, }); return { // Index-facing API - [self](const vast::table_slice& slice) { if (self->state.limit_ <= self->state.events_) return; auto remaining = self->state.limit_ - self->state.events_; auto ostream = std::make_unique<std::stringstream>(); auto writer = vast::format::json::writer{std::move(ostream), caf::settings{}}; - if (slice.rows() < remaining) - writer.write(slice); - else - writer.write(truncate(slice, remaining)); self->state.events_ += std::min<size_t>(slice.rows(), remaining); self->state.stringified_events_ += static_cast<std::stringstream&>(writer.out()).str(); Both of these errors should be handled. I propose the following change: ```suggestion if (slice.rows() > remaining) slice = truncate(std::move(slice), remaining); if (auto err = writer.write(slice)) { self->quit(std::move(err)); return; } ``` export_helper(export_helper_actor::stateful_pointer<export_helper_state> self, }); return { // Index-facing API + [self](vast::table_slice& slice) { if (self->state.limit_ <= self->state.events_) return; auto remaining = self->state.limit_ - self->state.events_; auto ostream = std::make_unique<std::stringstream>(); auto writer = vast::format::json::writer{std::move(ostream), caf::settings{}}; + if (slice.rows() > remaining) + slice = truncate(std::move(slice), remaining); + if (auto err = writer.write(slice)) { + self->quit(std::move(err)); + return; + } self->state.events_ += std::min<size_t>(slice.rows(), remaining); self->state.stringified_events_ += static_cast<std::stringstream&>(writer.out()).str();
codereview_new_cpp_data_10378
auto test_schema = record_type{ auto test_layout2 = record_type{ {"struct", record_type{ - {"foo", string_type{}, {"required"}}, {"bar", string_type{}} }}}; ```suggestion {"foo", type{string_type{}, {"required"}}}, ``` And then you no longer need the modification in type.hpp at all. auto test_schema = record_type{ auto test_layout2 = record_type{ {"struct", record_type{ + {"foo", type{string_type{}, {type::attribute_view{"required"}}}}, {"bar", string_type{}} }}};
codereview_new_cpp_data_10379
caf::expected<store_actor_plugin::builder_and_header> store_plugin::make_store_builder(system::accountant_actor accountant, system::filesystem_actor fs, const vast::uuid& id) const { - const auto& vast_config = caf::get<caf::settings>( - content(fs->home_system().config()).find("vast")->second); auto store = make_active_store(vast_config); if (!store) return store.error(); Does this still work if I provide no config at all, or do you de-reference a nullptr then? `find(...)->...` looks rather unsafe to me. Similarly, what happens if it's a string and not a dictionary? Doesn't `caf::get<caf::settings>` just run into undefined behavior (or an assertion) then? Since the configuration is user input we need to access it with rather defensive mechanisms. caf::expected<store_actor_plugin::builder_and_header> store_plugin::make_store_builder(system::accountant_actor accountant, system::filesystem_actor fs, const vast::uuid& id) const { + const auto& vast_config + = caf::get_or(content(fs->home_system().config()), "vast", caf::settings{}); auto store = make_active_store(vast_config); if (!store) return store.error();
codereview_new_cpp_data_10380
int main(int argc, char** argv) { } if (compression_level < min_level.ValueUnsafe() || compression_level > max_level.ValueUnsafe()) { - VAST_ERROR("zstd compression level '{}' outside of valid range [{}, {}]", compression_level, min_level.ValueUnsafe(), max_level.ValueUnsafe()); return EXIT_FAILURE; ```suggestion VAST_ERROR("Zstd compression level '{}' outside of valid range [{}, {}]", ``` int main(int argc, char** argv) { } if (compression_level < min_level.ValueUnsafe() || compression_level > max_level.ValueUnsafe()) { + VAST_ERROR("Zstd compression level '{}' outside of valid range [{}, {}]", compression_level, min_level.ValueUnsafe(), max_level.ValueUnsafe()); return EXIT_FAILURE;
codereview_new_cpp_data_10381
make_pipelines(pipelines_location location, const caf::settings& settings) { auto events = detail::unpack_config_list_to_vector<std::string>( (*pipeline)["events"]); if (!events) { - VAST_ERROR("Unable to extract events from pipeline config"); return events.error(); } auto server_pipeline = *location == "server"; Please stick to the usual noun-verb-object order for log messages here and start in lowercase. make_pipelines(pipelines_location location, const caf::settings& settings) { auto events = detail::unpack_config_list_to_vector<std::string>( (*pipeline)["events"]); if (!events) { + VAST_ERROR("Events extraction from pipeline config failed"); return events.error(); } auto server_pipeline = *location == "server";
codereview_new_cpp_data_10383
segment_builder::segment_builder(size_t initial_buffer_size, } caf::error segment_builder::add(table_slice x) { if (x.offset() == invalid_id) x.offset(num_events_); VAST_ASSERT(x.offset() == num_events_); This looks wrong. `num_events` should be equal `x.offset() + x.rows()`, but why do we even have to do any of this here? segment_builder::segment_builder(size_t initial_buffer_size, } caf::error segment_builder::add(table_slice x) { + // The index already sets the correct offset for this slice, but in some unit + // tests we test this component separately, causing incoming table slices not + // to have an offset at all. We should fix the unit tests properly, but that + // takes time we did not want to spend when migrating to partition-local ids. + // -- DL if (x.offset() == invalid_id) x.offset(num_events_); VAST_ASSERT(x.offset() == num_events_);
codereview_new_cpp_data_10384
class plugin final : public virtual transform_plugin { // transform plugin API [[nodiscard]] caf::expected<std::unique_ptr<transform_step>> make_transform_step(const record& options) const override { - if (!options.contains("fields") && !options.contains("schemas")) return caf::make_error(ec::invalid_configuration, "key 'fields' or 'schemas' is missing in " "configuration for drop step"); ```suggestion if (!(options.contains("fields") || options.contains("schemas"))) ``` Nit, but more idiomatic. class plugin final : public virtual transform_plugin { // transform plugin API [[nodiscard]] caf::expected<std::unique_ptr<transform_step>> make_transform_step(const record& options) const override { + if (!(options.contains("fields") || options.contains("schemas"))) return caf::make_error(ec::invalid_configuration, "key 'fields' or 'schemas' is missing in " "configuration for drop step");
codereview_new_cpp_data_10398
h2o_iovec_t h2o_url_normalize_path(h2o_mem_pool_t *pool, const char *path, size_ *query_at = SIZE_MAX; *norm_indexes = NULL; - if (len == 0 || (len == 1 && path[0] == '/')) { ret = h2o_iovec_init("/", 1); return ret; } Do we need this change? I think the code below would run fast when the input is "/". Basically, it tests if `path[0]` is `/` then skip the for loop. That is exactly the same as the or clause added here. h2o_iovec_t h2o_url_normalize_path(h2o_mem_pool_t *pool, const char *path, size_ *query_at = SIZE_MAX; *norm_indexes = NULL; + if (len == 0) { ret = h2o_iovec_init("/", 1); return ret; }
codereview_new_cpp_data_10520
UA_ServerConfig_clean(UA_ServerConfig *config) { #endif /* Logger */ if(config->logger.clear) config->logger.clear(config->logger.context); config->logger.log = NULL; Use `config->pLogger->clear` for the cleanup. Because some users will not set the normal config->logger at all. UA_ServerConfig_clean(UA_ServerConfig *config) { #endif /* Logger */ + if(config->logging != NULL) { + if((config->logging != &config->logger) && + (config->logging->clear != NULL)) { + config->logging->clear(config->logging->context); + } + config->logging = NULL; + } if(config->logger.clear) config->logger.clear(config->logger.context); config->logger.log = NULL;
codereview_new_cpp_data_10538
void Server_Card::resetState() setPT(QString()); setAnnotation(QString()); setDoesntUntap(false); - setFaceDown(false); } QString Server_Card::setAttribute(CardAttribute attribute, const QString &avalue, bool allCards) this causes a major bug: cards have their state reset when moved between the battlefield and the deck, their facedown state is then checked afterwards to determine what event to show to other players. with this change moving a facedown card to your deck (unknown to unknown) will tell all your opponents (but not you) what card it was. void Server_Card::resetState() setPT(QString()); setAnnotation(QString()); setDoesntUntap(false); } QString Server_Card::setAttribute(CardAttribute attribute, const QString &avalue, bool allCards)
codereview_new_cpp_data_10542
void Client::SetEXP(uint64 set_exp, uint64 set_aaxp, bool isrezzexp) { if (m_pp.exp != set_exp) { const auto xp_value = set_exp - m_pp.exp; - const auto export_string = fmt::format("{}",xp_value); - parse->EventPlayer(EVENT_XP_GAIN, this,export_string, xp_value); } if (m_pp.expAA != set_aaxp) { const auto aaxp_value = set_aaxp - m_pp.expAA; const auto export_string = fmt::format("{}",aaxp_value); - parse->EventPlayer(EVENT_AAXP_GAIN, this, export_string, aaxp_value); } //set the client's EXP and AAEXP Don't think you **need** to send it in `data` and `extradata` here, just one or the other is fine. Perl doesn't really care what you send it, so you can just send `data` and leave `extradata` as `0`. void Client::SetEXP(uint64 set_exp, uint64 set_aaxp, bool isrezzexp) { if (m_pp.exp != set_exp) { const auto xp_value = set_exp - m_pp.exp; + const auto export_string = fmt::format("{}", xp_value); + parse->EventPlayer(EVENT_EXP_GAIN, this, export_string, 0); } + if (m_pp.expAA != set_aaxp) { const auto aaxp_value = set_aaxp - m_pp.expAA; const auto export_string = fmt::format("{}",aaxp_value); + parse->EventPlayer(EVENT_AA_EXP_GAIN, this, export_string, 0); } //set the client's EXP and AAEXP
codereview_new_cpp_data_10543
void Mob::CommonDamage(Mob* attacker, int64 &damage, const uint16 spell_id, cons const auto has_npc_given_event = ( ( IsNPC() && - parse->HasQuestSub(CastToNPC()->GetNPCTypeID(), EVENT_DAMAGE_GIVEN, true) ) || ( attacker->IsNPC() && - parse->HasQuestSub(attacker->CastToNPC()->GetNPCTypeID(), EVENT_DAMAGE_GIVEN, true) ) ); const auto has_npc_taken_event = ( ( IsNPC() && - parse->HasQuestSub(CastToNPC()->GetNPCTypeID(), EVENT_DAMAGE_TAKEN, true) ) || ( attacker->IsNPC() && - parse->HasQuestSub(attacker->CastToNPC()->GetNPCTypeID(), EVENT_DAMAGE_TAKEN, true) ) ); - const auto has_player_given_event = parse->PlayerHasQuestSub(EVENT_DAMAGE_GIVEN, true); - const auto has_player_taken_event = parse->PlayerHasQuestSub(EVENT_DAMAGE_TAKEN, true); const auto has_given_event = ( has_bot_given_event || Seems like we should check encounters regardless, this is a very strange smell that maybe we should cut early void Mob::CommonDamage(Mob* attacker, int64 &damage, const uint16 spell_id, cons const auto has_npc_given_event = ( ( IsNPC() && + parse->HasQuestSub(CastToNPC()->GetNPCTypeID(), EVENT_DAMAGE_GIVEN) ) || ( attacker->IsNPC() && + parse->HasQuestSub(attacker->CastToNPC()->GetNPCTypeID(), EVENT_DAMAGE_GIVEN) ) ); const auto has_npc_taken_event = ( ( IsNPC() && + parse->HasQuestSub(CastToNPC()->GetNPCTypeID(), EVENT_DAMAGE_TAKEN) ) || ( attacker->IsNPC() && + parse->HasQuestSub(attacker->CastToNPC()->GetNPCTypeID(), EVENT_DAMAGE_TAKEN) ) ); + const auto has_player_given_event = parse->PlayerHasQuestSub(EVENT_DAMAGE_GIVEN); + const auto has_player_taken_event = parse->PlayerHasQuestSub(EVENT_DAMAGE_TAKEN); const auto has_given_event = ( has_bot_given_event ||
codereview_new_cpp_data_10544
bool SharedDatabase::GetInventory(uint32 char_id, EQ::InventoryProfile *inv) inst->SetCharges(charges); if (item->RecastDelay) { - if (item->RecastType != -1 && timestamps.count(item->RecastType)) { inst->SetRecastTimestamp(timestamps.at(item->RecastType)); - } else if (item->RecastType == -1 && timestamps.count(item->ID)) { inst->SetRecastTimestamp(timestamps.at(item->ID)); } else { Another spot for constant bool SharedDatabase::GetInventory(uint32 char_id, EQ::InventoryProfile *inv) inst->SetCharges(charges); if (item->RecastDelay) { + if (item->RecastType != RECAST_TYPE_UNLINKED_ITEM && timestamps.count(item->RecastType)) { inst->SetRecastTimestamp(timestamps.at(item->RecastType)); + } else if (item->RecastType == RECAST_TYPE_UNLINKED_ITEM && timestamps.count(item->ID)) { inst->SetRecastTimestamp(timestamps.at(item->ID)); } else {
codereview_new_cpp_data_10545
bool Mob::DoCastingChecksOnTarget(bool check_on_casting, int32 spell_id, Mob *sp } if (check_on_casting) { - if (spells[spell_id].target_type == ST_AEClientV1 || spells[spell_id].target_type == ST_AECaster || spells[spell_id].target_type == ST_Ring || Weird extra new line here. bool Mob::DoCastingChecksOnTarget(bool check_on_casting, int32 spell_id, Mob *sp } if (check_on_casting) { if (spells[spell_id].target_type == ST_AEClientV1 || spells[spell_id].target_type == ST_AECaster || spells[spell_id].target_type == ST_Ring ||
codereview_new_cpp_data_10546
bool Mob::CheckSpellLevelRestriction(Mob *caster, uint16 spell_id) bool can_cast = true; if (!caster) { - LogSpells("CheckSpellLevelRestriction: No caster"); return false; } Prefix log with `[CheckSpellLevelRestriction]` please vs `CheckSpellLevelRestriction:` bool Mob::CheckSpellLevelRestriction(Mob *caster, uint16 spell_id) bool can_cast = true; if (!caster) { + LogSpells("[CheckSpellLevelRestriction] No caster"); return false; }
codereview_new_cpp_data_10547
uint32 ZoneDatabase::GetDoorsCountPlusOne() int ZoneDatabase::GetDoorsDBCountPlusOne(std::string zone_short_name, int16 version) { const auto query = fmt::format( - "SELECT MAX(doorid) FROM doors " "WHERE zone = '{}' AND (version = {} OR version = -1)", zone_short_name, version Max can be null, shouldn't assume `std::stoi` will convert safely on its own in this edge case uint32 ZoneDatabase::GetDoorsCountPlusOne() int ZoneDatabase::GetDoorsDBCountPlusOne(std::string zone_short_name, int16 version) { const auto query = fmt::format( + "SELECT COALESCE(MAX(doorid), 0) FROM doors " "WHERE zone = '{}' AND (version = {} OR version = -1)", zone_short_name, version
codereview_new_cpp_data_10548
uint64 Client::CalcEXP(uint8 conlevel) { uint64 Client::GetExperienceForKill(Mob *against) { #ifdef LUA_EQEMU - uint32 lua_ret = 0; bool ignoreDefault = false; lua_ret = LuaParser::Instance()->GetExperienceForKill(this, against, ignoreDefault); `lua_ret` will need to be adjusted as well for the associated method ```cpp uint32 LuaParser::GetExperienceForKill(Client *self, Mob *against, bool &ignoreDefault) { uint32 retval = 0; for (auto &mod : mods_) { mod.GetExperienceForKill(self, against, retval, ignoreDefault); } return retval; } ``` This is for the lua mod system uint64 Client::CalcEXP(uint8 conlevel) { uint64 Client::GetExperienceForKill(Mob *against) { #ifdef LUA_EQEMU + uint64 lua_ret = 0; bool ignoreDefault = false; lua_ret = LuaParser::Instance()->GetExperienceForKill(this, against, ignoreDefault);
codereview_new_cpp_data_10549
const char *QuestEventSubroutines[_LargestEventID] = { "EVENT_AA_BUY", "EVENT_AA_GAIN", "EVENT_PAYLOAD", - "EVENT_LEVEL_DOWN" - #ifdef BOTS - , "EVENT_SPELL_EFFECT_BOT", - "EVENT_SPELL_EFFECT_BUFF_TIC_BOT" #endif }; nit: I'd remove this floating comma and just put it at the end of `EVENT_LEVEL_DOWN` (and probably one after `EVENT_SPELL_EFFECT_BUFF_TIC_BOT`). Even if BOTS is undefined the comma at the end will make it cleaner when adding new events since only one new line will need added. Also remove the indent from `#ifdef BOTS` const char *QuestEventSubroutines[_LargestEventID] = { "EVENT_AA_BUY", "EVENT_AA_GAIN", "EVENT_PAYLOAD", + "EVENT_LEVEL_DOWN", +#ifdef BOTS "EVENT_SPELL_EFFECT_BOT", + "EVENT_SPELL_EFFECT_BUFF_TIC_BOT", #endif };
codereview_new_cpp_data_10550
bool RuleManager::SetRule(const std::string &rule_name, const std::string &rule_ LogRules("Set rule [{}] to value [{}]", rule_name, m_RuleIntValues[index]); break; case RealRule: - m_RuleRealValues[index] = std::stof(rule_value); LogRules("Set rule [{}] to value [{:.2f}]", rule_name, m_RuleRealValues[index]); break; case BoolRule: This one can throw on bad input now too bool RuleManager::SetRule(const std::string &rule_name, const std::string &rule_ LogRules("Set rule [{}] to value [{}]", rule_name, m_RuleIntValues[index]); break; case RealRule: + m_RuleRealValues[index] = atof(rule_value); LogRules("Set rule [{}] to value [{:.2f}]", rule_name, m_RuleRealValues[index]); break; case BoolRule:
codereview_new_cpp_data_10551
bool Bot::AICastSpell(Mob* tar, uint8 iChance, uint32 iSpellTypes) { // TODO: Add ST_TargetsTarget support for Buffing. if (!((spells[selectedBotSpell.SpellId].target_type == ST_Target || spells[selectedBotSpell.SpellId].target_type == ST_Pet || - (tar == this && !spells[selectedBotSpell.SpellId].target_type == ST_TargetsTarget) || spells[selectedBotSpell.SpellId].target_type == ST_Group || spells[selectedBotSpell.SpellId].target_type == ST_GroupTeleport || (botClass == BARD && spells[selectedBotSpell.SpellId].target_type == ST_AEBard)) && != versus ! On spells part. bool Bot::AICastSpell(Mob* tar, uint8 iChance, uint32 iSpellTypes) { // TODO: Add ST_TargetsTarget support for Buffing. if (!((spells[selectedBotSpell.SpellId].target_type == ST_Target || spells[selectedBotSpell.SpellId].target_type == ST_Pet || + (tar == this && spells[selectedBotSpell.SpellId].target_type != ST_TargetsTarget) || spells[selectedBotSpell.SpellId].target_type == ST_Group || spells[selectedBotSpell.SpellId].target_type == ST_GroupTeleport || (botClass == BARD && spells[selectedBotSpell.SpellId].target_type == ST_AEBard)) &&
codereview_new_cpp_data_10552
void Bot::PerformTradeWithClient(int16 begin_slot_id, int16 end_slot_id, Client* } } - bool bots_ignore_race = RuleB(Bot, AllowBotEquipAnyRaceGear); - if (!trade_instance->IsClassEquipable(GetClass()) || (GetLevel() < trade_instance->GetItem()->ReqLevel) || (!trade_instance->IsRaceEquipable(GetRace()) && !bots_ignore_race)) { // deity checks will be handled within IsEquipable() if (trade_event_exists) { event_trade.push_back(ClientTrade(trade_instance, trade_index)); continue; ```cpp GetLevel() < trade_instance->GetItem()->ReqLevel ``` versus ```cpp (GetLevel() < trade_instance->GetItem()->ReqLevel) ``` void Bot::PerformTradeWithClient(int16 begin_slot_id, int16 end_slot_id, Client* } } + if (!trade_instance->IsClassEquipable(GetClass()) || GetLevel() < trade_instance->GetItem()->ReqLevel || (!trade_instance->IsRaceEquipable(GetRace()) && !RuleB(Bot, AllowBotEquipAnyRaceGear))) { // deity checks will be handled within IsEquipable() if (trade_event_exists) { event_trade.push_back(ClientTrade(trade_instance, trade_index)); continue;
codereview_new_cpp_data_10553
std::string Zone::GetAAName(int aa_id) int current_aa_id = 0; - for (const auto& r : aa_ranks) { - if (r.second.get()->id == aa_id && r.second.get()->base_ability) { - current_aa_id = r.second.get()->base_ability->id; - break; - } } if (current_aa_id) { - if (aa_abilities.find(current_aa_id) != aa_abilities.end()) { - return aa_abilities.find(current_aa_id)->second.get()->name; } } Should be able to just `.find(aa_id)` instead of looping to find it since it looks like the id is the hash key for `Zone::aa_ranks` unless I'm missing something std::string Zone::GetAAName(int aa_id) int current_aa_id = 0; + const auto& r = aa_ranks.find(aa_id); + if ( + r != aa_ranks.end() && + r->second.get()->base_ability + ) { + current_aa_id = r->second.get()->base_ability->id; } if (current_aa_id) { + const auto& a = aa_abilities.find(current_aa_id); + if (a != aa_abilities.end()) { + return a->second.get()->name; } }
codereview_new_cpp_data_10554
std::vector<int> Client::GetScribeableSpells(uint8 min_level, uint8 max_level) { if (spells[spell_id].spell_group) { uint32 highest_spell_id = GetHighestSpellinSpellGroup(spells[spell_id].spell_group); - if (spells[highest_spell_id].classes[m_pp.class_ - 1] <= max_level) { - if (spells[highest_spell_id].classes[m_pp.class_ - 1] >= min_level) { - if (spell_id != highest_spell_id) { - continue; - } - } } } Can consolidate the conditions being they all have to occur. ```cpp if (spells[spell_id].spell_group) { uint32 highest_spell_id = GetHighestSpellinSpellGroup(spells[spell_id].spell_group); if ( spells[highest_spell_id].classes[m_pp.class_ - 1] >= min_level && spells[highest_spell_id].classes[m_pp.class_ - 1] <= max_level && spell_id != highest_spell_id ) { continue; } } ``` std::vector<int> Client::GetScribeableSpells(uint8 min_level, uint8 max_level) { if (spells[spell_id].spell_group) { uint32 highest_spell_id = GetHighestSpellinSpellGroup(spells[spell_id].spell_group); + if ( + spells[highest_spell_id].classes[m_pp.class_ - 1] >= min_level && + spells[highest_spell_id].classes[m_pp.class_ - 1] <= max_level && + spell_id != highest_spell_id + ) { + continue; } }
codereview_new_cpp_data_10555
uint32 Client::GetHighestSpellinSpellGroup(uint32 spell_group) int highest_rank = 0; //highest ranked found in spellgroup uint32 highest_spell_id = 0; //spell_id of the highest ranked spell - for (int i = 0; i < EQ::spells::SPELL_ID_MAX; i++) { - if (IsValidSpell(i)) { - if (spells[i].spell_group == spell_group) { - if (highest_rank < spells[i].rank) { - highest_rank = spells[i].rank; - highest_spell_id = i; - } - } } } return highest_spell_id; } Consolidation similar to above. ```cpp uint32 Client::GetHighestSpellinSpellGroup(uint32 spell_group) { //Typical live spells follow 1/5/10 rank value for actual ranks 1/2/3, but this can technically be set as anything. int highest_rank = 0; //highest ranked found in spellgroup uint32 highest_spell_id = 0; //spell_id of the highest ranked spell for (uint16 i = 0; i < SPDAT_RECORDS; i++) { if ( IsValidSpell(i) && spells[i].spell_group == spell_group && highest_rank < spells[i].rank ) { highest_rank = spells[i].rank; highest_spell_id = i; } } return highest_spell_id; } ``` uint32 Client::GetHighestSpellinSpellGroup(uint32 spell_group) int highest_rank = 0; //highest ranked found in spellgroup uint32 highest_spell_id = 0; //spell_id of the highest ranked spell + for (int i = 0; i < SPDAT_RECORDS; i++) { + if ( + IsValidSpell(i) && + spells[i].spell_group == spell_group && + highest_rank < spells[i].rank + ) { + highest_rank = spells[i].rank; + highest_spell_id = i; } } + return highest_spell_id; }
codereview_new_cpp_data_10556
NPC::NPC(const NPCType *npc_type_data, Spawn2 *in_respawn, const glm::vec4 &posi // lava dragon is a fixed size model and should always use its default // otherwise pathing issues if (race == RACE_LAVA_DRAGON_49) { - size = 6; } taunting = false; Should this be 5 since you said size is 5? NPC::NPC(const NPCType *npc_type_data, Spawn2 *in_respawn, const glm::vec4 &posi // lava dragon is a fixed size model and should always use its default // otherwise pathing issues if (race == RACE_LAVA_DRAGON_49) { + size = 5; } taunting = false;
codereview_new_cpp_data_10557
void Client::SetStartZone(uint32 zoneid, float x, float y, float z, float headin } if (x == 0 && y == 0 && z == 0) { - auto zd = GetZoneVersionWithFallback(m_pp.binds[4].zone_id); if (zd.id > 0) { m_pp.binds[4].x = zd.safe_x; m_pp.binds[4].y = zd.safe_y; GetZone() instead maybe since it's not using version here? void Client::SetStartZone(uint32 zoneid, float x, float y, float z, float headin } if (x == 0 && y == 0 && z == 0) { + auto zd = GetZone(m_pp.binds[4].zone_id); if (zd.id > 0) { m_pp.binds[4].x = zd.safe_x; m_pp.binds[4].y = zd.safe_y;