id stringlengths 27 29 | content stringlengths 226 3.24k |
|---|---|
codereview_new_cpp_data_4620 | namespace
std::array<int, maxVolume + 1> result{ 0 };
result[maxVolume] = MIX_MAX_VOLUME;
for ( int i = 1; i < maxVolume; i++ )
- result[i] = round( a * std::pow( 10.0, i * b ) * MIX_MAX_VOLUME );
return result;
}
();
:warning: **clang\-diagnostic\-float\-conversion** :warning:
implicit conversion turns floating\-point number into integer: `` double `` to `` std::array<int, 11>::value_type `` \(aka `` int ``\)
namespace
std::array<int, maxVolume + 1> result{ 0 };
result[maxVolume] = MIX_MAX_VOLUME;
for ( int i = 1; i < maxVolume; i++ )
+ result[i] = static_cast<int>( round( a * std::pow( 10.0, i * b ) * MIX_MAX_VOLUME ) );
return result;
}
(); |
codereview_new_cpp_data_4621 | namespace
return MIX_MAX_VOLUME;
}
- return ( std::exp( std::log( 10 + 1 ) * volumePercentage / 100 ) - 1 ) / 10 * MIX_MAX_VOLUME;
}
}
:warning: **bugprone\-narrowing\-conversions** :warning:
narrowing conversion from `` double `` to `` int ``
namespace
return MIX_MAX_VOLUME;
}
+ return ( static_cast<int>( std::exp( std::log( 10 + 1 ) * volumePercentage / 100 ) - 1 ) / 10 * MIX_MAX_VOLUME );
}
}
|
codereview_new_cpp_data_4622 | namespace
return MIX_MAX_VOLUME;
}
- return ( std::exp( std::log( 10 + 1 ) * volumePercentage / 100 ) - 1 ) / 10 * MIX_MAX_VOLUME;
}
}
:warning: **clang\-diagnostic\-float\-conversion** :warning:
implicit conversion turns floating\-point number into integer: `` double `` to `` int ``
namespace
return MIX_MAX_VOLUME;
}
+ return ( static_cast<int>( std::exp( std::log( 10 + 1 ) * volumePercentage / 100 ) - 1 ) / 10 * MIX_MAX_VOLUME );
}
}
|
codereview_new_cpp_data_4623 | bool System::Unlink( const std::string & path )
}
#if !defined( _WIN32 ) && !defined( ANDROID )
-// TODO: Android filesystem is case-sensitive so it should use the code below.
-// However, in Android an application has access only to a specific path on the system.
-
// based on: https://github.com/OneSadCookie/fcaseopen
bool System::GetCaseInsensitivePath( const std::string & path, std::string & correctedPath )
{
BTW, Android filesystem is in fact case-insensitive, at least in those places that are accessible by users (`/sdcard`) and where game data files are placed. We don't need to use the workarounds for this.
bool System::Unlink( const std::string & path )
}
#if !defined( _WIN32 ) && !defined( ANDROID )
// based on: https://github.com/OneSadCookie/fcaseopen
bool System::GetCaseInsensitivePath( const std::string & path, std::string & correctedPath )
{ |
codereview_new_cpp_data_4624 | namespace
bool fullScreen = true;
uint32_t flags = SDL_GetWindowFlags( _window );
- static_assert( ( SDL_WINDOW_FULLSCREEN_DESKTOP & SDL_WINDOW_FULLSCREEN ) == SDL_WINDOW_FULLSCREEN && SDL_WINDOW_FULLSCREEN_DESKTOP > SDL_WINDOW_FULLSCREEN,
- "SDL Enumeration definition has changed. Make sure that order of enumeration entries goes from highest value to lowest." );
- if ( ( flags & SDL_WINDOW_FULLSCREEN_DESKTOP ) == SDL_WINDOW_FULLSCREEN_DESKTOP ) {
flags &= ~SDL_WINDOW_FULLSCREEN_DESKTOP;
-
- fullScreen = false;
- }
- else if ( ( flags & SDL_WINDOW_FULLSCREEN ) == SDL_WINDOW_FULLSCREEN ) {
flags &= ~SDL_WINDOW_FULLSCREEN;
fullScreen = false;
Hi @ihhub why just not check if either one of these flags is set, and if yes, then just clear both flags at once? In this case we shouldn't depend on the order of flag values as well as whether they intersect or not. Or is it not working for some reason?
namespace
bool fullScreen = true;
uint32_t flags = SDL_GetWindowFlags( _window );
+ if ( ( flags & SDL_WINDOW_FULLSCREEN ) == SDL_WINDOW_FULLSCREEN || ( flags & SDL_WINDOW_FULLSCREEN_DESKTOP ) == SDL_WINDOW_FULLSCREEN_DESKTOP ) {
flags &= ~SDL_WINDOW_FULLSCREEN_DESKTOP;
flags &= ~SDL_WINDOW_FULLSCREEN;
fullScreen = false; |
codereview_new_cpp_data_4625 | Battle::Interface::Interface( Arena & a, int32_t center )
// hexagon
sf_hexagon = DrawHexagon( fheroes2::GetColorId( 0x68, 0x8C, 0x04 ) );
- sf_cursor = DrawHexagonShadow( 4 );
sf_shadow = DrawHexagonShadow( 4 );
btn_auto.setICNInfo( ICN::TEXTBAR, 4, 5 );
Could you please explain this change?
Battle::Interface::Interface( Arena & a, int32_t center )
// hexagon
sf_hexagon = DrawHexagon( fheroes2::GetColorId( 0x68, 0x8C, 0x04 ) );
+ sf_cursor = DrawHexagonShadow( 2 );
sf_shadow = DrawHexagonShadow( 4 );
btn_auto.setICNInfo( ICN::TEXTBAR, 4, 5 ); |
codereview_new_cpp_data_4626 | void LocalEvent::setEventProcessingStates()
// TODO: we don't process this event. Add the logic.
setEventProcessingState( SDL_TEXTINPUT, false );
setEventProcessingState( SDL_KEYMAPCHANGED, false );
- setEventProcessingState( SDL_TEXTEDITING_EXT, false );
setEventProcessingState( SDL_MOUSEMOTION, true );
setEventProcessingState( SDL_MOUSEBUTTONDOWN, true );
setEventProcessingState( SDL_MOUSEBUTTONUP, true );
:warning: **clang\-diagnostic\-error** :warning:
use of undeclared identifier `` SDL_TEXTEDITING_EXT ``; did you mean `` SDL_TEXTEDITING ``?
```suggestion
setEventProcessingState( SDL_TEXTEDITING_EXT, false );SDL_TEXTEDITING
```
void LocalEvent::setEventProcessingStates()
// TODO: we don't process this event. Add the logic.
setEventProcessingState( SDL_TEXTINPUT, false );
setEventProcessingState( SDL_KEYMAPCHANGED, false );
+ // SDL_TEXTEDITING_EXT is supported only from SDL 2.0.22
setEventProcessingState( SDL_MOUSEMOTION, true );
setEventProcessingState( SDL_MOUSEBUTTONDOWN, true );
setEventProcessingState( SDL_MOUSEBUTTONUP, true ); |
codereview_new_cpp_data_4627 | namespace
if ( tempCursor == nullptr ) {
ERROR_LOG( "Failed to create a cursor. The error description: " << SDL_GetError() )
}
- SDL_SetCursor( tempCursor );
const int returnCode = SDL_ShowCursor( _show ? SDL_ENABLE : SDL_DISABLE );
if ( returnCode < 0 ) {
Should we call `SDL_SetCursor()` with null cursor here? I know that there will be no harm, but is this needed for some reason?
namespace
if ( tempCursor == nullptr ) {
ERROR_LOG( "Failed to create a cursor. The error description: " << SDL_GetError() )
}
+ else {
+ SDL_SetCursor( tempCursor );
+ }
const int returnCode = SDL_ShowCursor( _show ? SDL_ENABLE : SDL_DISABLE );
if ( returnCode < 0 ) { |
codereview_new_cpp_data_4628 | namespace
released[20].resize( 8 + offset * 2, 10 + offset * 2 );
released[20].reset();
fheroes2::DrawLine( released[20], { offset + 0, offset + 4 }, { offset + 4, offset + 0 }, buttonGoodReleasedColor );
- fheroes2::DrawLi19ne( released[20], { offset + 5, offset + 0 }, { offset + 5, offset + 4 }, buttonGoodReleasedColor );
fheroes2::DrawLine( released[20], { offset + 5, offset + 6 }, { offset + 5, offset + 8 }, buttonGoodReleasedColor );
fheroes2::DrawLine( released[20], { offset + 0, offset + 5 }, { offset + 7, offset + 5 }, buttonGoodReleasedColor );
fheroes2::DrawLine( released[20], { offset + 3, offset + 9 }, { offset + 7, offset + 9 }, buttonGoodReleasedColor );
:warning: **clang\-diagnostic\-error** :warning:
no member named `` DrawLi19ne `` in namespace `` fheroes2 ``; did you mean `` DrawLine ``?
```suggestion
fheroes2::DrawLine( released[20], { offset + 5, offset + 0 }, { offset + 5, offset + 4 }, buttonGoodReleasedColor );
```
namespace
released[20].resize( 8 + offset * 2, 10 + offset * 2 );
released[20].reset();
fheroes2::DrawLine( released[20], { offset + 0, offset + 4 }, { offset + 4, offset + 0 }, buttonGoodReleasedColor );
+ fheroes2::DrawLine( released[20], { offset + 5, offset + 0 }, { offset + 5, offset + 4 }, buttonGoodReleasedColor );
fheroes2::DrawLine( released[20], { offset + 5, offset + 6 }, { offset + 5, offset + 8 }, buttonGoodReleasedColor );
fheroes2::DrawLine( released[20], { offset + 0, offset + 5 }, { offset + 7, offset + 5 }, buttonGoodReleasedColor );
fheroes2::DrawLine( released[20], { offset + 3, offset + 9 }, { offset + 7, offset + 9 }, buttonGoodReleasedColor ); |
codereview_new_cpp_data_4629 | namespace fheroes2
SupportedLanguage getCurrentLanguage()
{
- const Settings & conf = Settings::Get();
-
- const fheroes2::SupportedLanguage currentLanguage = fheroes2::getLanguageFromAbbreviation( conf.getGameLanguage() );
- return currentLanguage;
}
}
We can directly return the value of this function call without the need of a temporary variable.
namespace fheroes2
SupportedLanguage getCurrentLanguage()
{
+ return fheroes2::getLanguageFromAbbreviation( Settings::Get().getGameLanguage() );
}
} |
codereview_new_cpp_data_4630 | void Troops::JoinTroops( Troops & troops2 )
}
}
-void Troops::MoveTroops( Troops & from, const int monsterIdToKeep, const bool moveAll )
{
assert( this != &from );
// Combine troops of the same type in one slot to leave more room for new troops to join
MergeSameMonsterTroops();
- if ( !moveAll ) {
assert( isValid() && from.isValid() );
}
:warning: **clang\-diagnostic\-error** :warning:
out\-of\-line definition of `` MoveTroops `` does not match any declaration in `` Troops ``
void Troops::JoinTroops( Troops & troops2 )
}
}
+void Troops::MoveTroops( Troops & from, const int monsterIdToKeep, const bool castleMove )
{
assert( this != &from );
// Combine troops of the same type in one slot to leave more room for new troops to join
MergeSameMonsterTroops();
+ if ( !castleMove ) {
assert( isValid() && from.isValid() );
}
|
codereview_new_cpp_data_4631 | Castle::CastleDialogReturnValue Castle::OpenDialog( const bool readOnly, const b
}
// Move troops up.
else if ( HotKeyPressEvent( Game::HotKeyEvent::MOVE_TOP ) ) {
- GetArmy().MoveTroops( heroes.Guest()->GetArmy(), keep ? keep->GetID() : Monster::UNKNOWN, false );
redrawAfterArmyAction = true;
}
}
:warning: **clang\-diagnostic\-error** :warning:
too many arguments to function call, expected 2, have 3
Castle::CastleDialogReturnValue Castle::OpenDialog( const bool readOnly, const b
}
// Move troops up.
else if ( HotKeyPressEvent( Game::HotKeyEvent::MOVE_TOP ) ) {
+ GetArmy().MoveTroops( heroes.Guest()->GetArmy(), keep ? keep->GetID() : Monster::UNKNOWN, true );
redrawAfterArmyAction = true;
}
} |
codereview_new_cpp_data_4632 | bool Troops::JoinTroop( const Troop & troop )
return JoinTroop( troop.GetMonster(), troop.GetCount(), false );
}
-}
bool Troops::AllTroopsAreTheSame() const
{
:warning: **clang\-diagnostic\-error** :warning:
extraneous closing brace \(`` } ``\)
bool Troops::JoinTroop( const Troop & troop )
return JoinTroop( troop.GetMonster(), troop.GetCount(), false );
}
bool Troops::AllTroopsAreTheSame() const
{ |
codereview_new_cpp_data_4633 | namespace
bool Game::AutoSaveAtTheBeginningOfTheDay()
{
- return Game::Save( System::ConcatPath( GetSaveDir(), autoSaveNameAtTheBeginningOfTheDay + GetSaveFileExtension() ), true );
}
bool Game::AutoSaveAtTheEndOfTheDay()
{
- return Game::Save( System::ConcatPath( GetSaveDir(), autoSaveNameAtTheEndOfTheDay + GetSaveFileExtension() ), true );
}
bool Game::Save( const std::string & fn, const bool autoSave /* = false */ )
:warning: **clang\-diagnostic\-error** :warning:
no member named `` ConcatPath `` in namespace `` System ``; did you mean `` concatPath ``?
```suggestion
return Game::Save( System::concatPath( GetSaveDir(), autoSaveNameAtTheBeginningOfTheDay + GetSaveFileExtension() ), true );
```
namespace
bool Game::AutoSaveAtTheBeginningOfTheDay()
{
+ return Game::Save( System::concatPath( GetSaveDir(), autoSaveNameAtTheBeginningOfTheDay + GetSaveFileExtension() ), true );
}
bool Game::AutoSaveAtTheEndOfTheDay()
{
+ return Game::Save( System::concatPath( GetSaveDir(), autoSaveNameAtTheEndOfTheDay + GetSaveFileExtension() ), true );
}
bool Game::Save( const std::string & fn, const bool autoSave /* = false */ ) |
codereview_new_cpp_data_4634 | namespace
bool Game::AutoSaveAtTheBeginningOfTheDay()
{
- return Game::Save( System::ConcatPath( GetSaveDir(), autoSaveNameAtTheBeginningOfTheDay + GetSaveFileExtension() ), true );
}
bool Game::AutoSaveAtTheEndOfTheDay()
{
- return Game::Save( System::ConcatPath( GetSaveDir(), autoSaveNameAtTheEndOfTheDay + GetSaveFileExtension() ), true );
}
bool Game::Save( const std::string & fn, const bool autoSave /* = false */ )
:warning: **clang\-diagnostic\-error** :warning:
no member named `` ConcatPath `` in namespace `` System ``; did you mean `` concatPath ``?
```suggestion
return Game::Save( System::concatPath( GetSaveDir(), autoSaveNameAtTheEndOfTheDay + GetSaveFileExtension() ), true );
```
namespace
bool Game::AutoSaveAtTheBeginningOfTheDay()
{
+ return Game::Save( System::concatPath( GetSaveDir(), autoSaveNameAtTheBeginningOfTheDay + GetSaveFileExtension() ), true );
}
bool Game::AutoSaveAtTheEndOfTheDay()
{
+ return Game::Save( System::concatPath( GetSaveDir(), autoSaveNameAtTheEndOfTheDay + GetSaveFileExtension() ), true );
}
bool Game::Save( const std::string & fn, const bool autoSave /* = false */ ) |
codereview_new_cpp_data_4635 | namespace
// The width of text area is only 16 pixels.
void getCustomNormalButton( fheroes2::Sprite & released, fheroes2::Sprite & pressed, const bool isEvilInterface, int32_t width, fheroes2::Point & releasedOffset,
- fheroes2::Point & pressedOffset)
{
assert( width > 0 );
:warning: **misc\-no\-recursion** :warning:
function `` getCustomNormalButton `` is within a recursive call chain
namespace
// The width of text area is only 16 pixels.
void getCustomNormalButton( fheroes2::Sprite & released, fheroes2::Sprite & pressed, const bool isEvilInterface, int32_t width, fheroes2::Point & releasedOffset,
+ fheroes2::Point & pressedOffset )
{
assert( width > 0 );
|
codereview_new_cpp_data_4636 | namespace
}
else {
const int32_t middleWidth = originalWidth / 3;
- const int32_t startMiddleX = middleWidth;
const int32_t overallMiddleWidth = width - middleWidth * 2;
const int32_t middleWidthCount = overallMiddleWidth / middleWidth;
const int32_t middleLeftOver = overallMiddleWidth - middleWidthCount * middleWidth;
:warning: **clang\-diagnostic\-unused\-variable** :warning:
unused variable `` startMiddleX ``
namespace
}
else {
const int32_t middleWidth = originalWidth / 3;
const int32_t overallMiddleWidth = width - middleWidth * 2;
const int32_t middleWidthCount = overallMiddleWidth / middleWidth;
const int32_t middleLeftOver = overallMiddleWidth - middleWidthCount * middleWidth; |
codereview_new_cpp_data_4637 | 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\-error** :warning:
expected `` ; `` at end of declaration
```suggestion
TextBox title(; _( "Support us at ), Font::BIG, textWidth );
```
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_4638 | 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\-error** :warning:
unterminated function\-like macro invocation
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_4639 | 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 );
```suggestion
TextBox title( _( "Support us at" ), Font::BIG, textWidth );
```
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_4640 | void Heroes::MeetingDialog( Heroes & otherHero )
display.render();
}
- else if ( le.MouseClickLeft( moveArmyToHero1.area() ) HotKeyHoldEvent( Game::HotKeyEvent::MOVE_LEFT ) ) {
const ArmyTroop * keep = nullptr;
if ( selectArmy1.isSelected() ) {
:warning: **clang\-diagnostic\-error** :warning:
expected `` ) ``
void Heroes::MeetingDialog( Heroes & otherHero )
display.render();
}
+ else if ( le.MouseClickLeft( moveArmyToHero1.area() ) || HotKeyHoldEvent( Game::HotKeyEvent::MOVE_LEFT ) ) {
const ArmyTroop * keep = nullptr;
if ( selectArmy1.isSelected() ) { |
codereview_new_cpp_data_4641 | NeutralMonsterJoiningCondition Army::GetJoinSolution( const Heroes & hero, const
}
// Neutral monsters don't care about hero's stats. Ignoring hero's stats makes hero's army strength be smaller in eyes of neutrals and they won't join so often.
- const double armyStrengthRatio = hero.GetArmy().getTroops().GetStrength() / troop.GetStrength();
// The ability to accept monsters (a free slot or a stack of monsters of the same type) is a
// mandatory condition for their joining in accordance with the mechanics of the original game
Hi @ihhub are you sure that this will work? `Army::getTroops()` returns a reference, and `Troops::GetStrength()` is `virtual`, so `Army::GetStrength()` [will be called anyway](https://godbolt.org/z/rTqrcWqGY). The proper fix should be:
```cpp
hero.GetArmy().Troops::GetStrength()
```
NeutralMonsterJoiningCondition Army::GetJoinSolution( const Heroes & hero, const
}
// Neutral monsters don't care about hero's stats. Ignoring hero's stats makes hero's army strength be smaller in eyes of neutrals and they won't join so often.
+ const double armyStrengthRatio = hero.GetArmy().Troops::GetStrength() / troop.GetStrength();
// The ability to accept monsters (a free slot or a stack of monsters of the same type) is a
// mandatory condition for their joining in accordance with the mechanics of the original game |
codereview_new_cpp_data_4642 | namespace AI
Troop * unitToSwap = heroArmy.GetSlowestTroop();
if ( unitToSwap ) {
// We need to compare a strength of troops excluding hero's stats.
- const double troopsStrength = Troops( heroArmy ).GetStrength();
const double significanceRatio = isFigtherHero ? 20.0 : 10.0;
if ( unitToSwap->GetStrength() > troopsStrength / significanceRatio ) {
:warning: **cppcoreguidelines\-slicing** :warning:
slicing object from type `` Army `` to `` Troops `` discards 24 bytes of state
namespace AI
Troop * unitToSwap = heroArmy.GetSlowestTroop();
if ( unitToSwap ) {
// We need to compare a strength of troops excluding hero's stats.
+ const double troopsStrength = Troops( heroArmy.getTroops() ).GetStrength();
const double significanceRatio = isFigtherHero ? 20.0 : 10.0;
if ( unitToSwap->GetStrength() > troopsStrength / significanceRatio ) { |
codereview_new_cpp_data_4643 | NeutralMonsterJoiningCondition Army::GetJoinSolution( const Heroes & hero, const
}
// Neutral monsters don't care about hero's stats. Ignoring hero's stats makes hero's army strength be smaller in eyes of neutrals and they won't join so often.
- const double armyStrengthRatio = Troops( hero.GetArmy() ).GetStrength() / troop.GetStrength();
// The ability to accept monsters (a free slot or a stack of monsters of the same type) is a
// mandatory condition for their joining in accordance with the mechanics of the original game
:warning: **cppcoreguidelines\-slicing** :warning:
slicing object from type `` Army `` to `` Troops `` discards 24 bytes of state
NeutralMonsterJoiningCondition Army::GetJoinSolution( const Heroes & hero, const
}
// Neutral monsters don't care about hero's stats. Ignoring hero's stats makes hero's army strength be smaller in eyes of neutrals and they won't join so often.
+ const double armyStrengthRatio = Troops( hero.GetArmy().getTroops() ).GetStrength() / troop.GetStrength();
// The ability to accept monsters (a free slot or a stack of monsters of the same type) is a
// mandatory condition for their joining in accordance with the mechanics of the original game |
codereview_new_cpp_data_4644 | double Heroes::getAIMininumJoiningArmyStrength() const
break;
}
- return strengthThreshold * Troops( GetArmy() ).GetStrength();
}
StreamBase & operator<<( StreamBase & msg, const VecHeroes & heroes )
:warning: **cppcoreguidelines\-slicing** :warning:
slicing object from type `` Army `` to `` Troops `` discards 24 bytes of state
double Heroes::getAIMininumJoiningArmyStrength() const
break;
}
+ return strengthThreshold * Troops( GetArmy().getTroops() ).GetStrength();
}
StreamBase & operator<<( StreamBase & msg, const VecHeroes & heroes ) |
codereview_new_cpp_data_4645 | int Castle::DialogBuyHero( const Heroes * hero ) const
dst_pt.y = dst_pt.y + recruitHeroText.h() + spacer;
fheroes2::Blit( portrait_frame, display, dst_pt.x, dst_pt.y );
- fheroes2::Rect heroPortraitArea( dst_pt.x, dst_pt.y, portrait_frame.width(), portrait_frame.height() );
dst_pt.x = dst_pt.x + 5;
dst_pt.y = dst_pt.y + 6;
hero->PortraitRedraw( dst_pt.x, dst_pt.y, PORT_BIG, display );
Please make this variable `const`.
int Castle::DialogBuyHero( const Heroes * hero ) const
dst_pt.y = dst_pt.y + recruitHeroText.h() + spacer;
fheroes2::Blit( portrait_frame, display, dst_pt.x, dst_pt.y );
+ const fheroes2::Rect heroPortraitArea( dst_pt.x, dst_pt.y, portrait_frame.width(), portrait_frame.height() );
dst_pt.x = dst_pt.x + 5;
dst_pt.y = dst_pt.y + 6;
hero->PortraitRedraw( dst_pt.x, dst_pt.y, PORT_BIG, display ); |
codereview_new_cpp_data_4646 | void Dialog::QuickInfo( const HeroBase & hero, const fheroes2::Point & position
const Kingdom & kingdom = world.GetKingdom( conf.CurrentColor() );
const bool isFriend = ColorBase( hero.GetColor() ).isFriends( conf.CurrentColor() );
const bool isUnderIdentifyHeroSpell = kingdom.Modes( Kingdom::IDENTIFYHERO );
- const bool showFullInfo = hero.GetColor() == 0 || isFriend || isUnderIdentifyHeroSpell || kingdom.IsTileVisibleFromCrystalBall( hero.GetIndex() );
const Heroes * activeHero = dynamic_cast<const Heroes *>( &hero );
const Captain * activeCaptain = dynamic_cast<const Captain *>( &hero );
Please avoid using hardcoded values. Use `Color::NONE` instead of `0`. Also add parenthesis for the newly added statement.
void Dialog::QuickInfo( const HeroBase & hero, const fheroes2::Point & position
const Kingdom & kingdom = world.GetKingdom( conf.CurrentColor() );
const bool isFriend = ColorBase( hero.GetColor() ).isFriends( conf.CurrentColor() );
const bool isUnderIdentifyHeroSpell = kingdom.Modes( Kingdom::IDENTIFYHERO );
+ const bool isNeutralHero = ( hero.GetColor() == Color::NONE );
+ const bool showFullInfo = isNeutralHero || isFriend || isUnderIdentifyHeroSpell || kingdom.IsTileVisibleFromCrystalBall( hero.GetIndex() );
const Heroes * activeHero = dynamic_cast<const Heroes *>( &hero );
const Captain * activeCaptain = dynamic_cast<const Captain *>( &hero ); |
codereview_new_cpp_data_4647 | 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_4648 | void Battle::Unit::SpellRestoreAction( const Spell & spell, uint32_t spoint, con
SetPosition( GetPosition() );
if ( Arena::GetInterface() ) {
- std::string str( _( "%{count} %{name} rise from the dead!" ) );
- str = _n( "%{count} %{name} rises from the dead!", "%{count} %{name} rise from the dead!", %{count} );
StringReplace( str, "%{count}", resurrect );
StringReplace( str, "%{name}", GetName() );
Arena::GetInterface()->SetStatus( str, true );
:warning: **clang\-diagnostic\-error** :warning:
expected expression
void Battle::Unit::SpellRestoreAction( const Spell & spell, uint32_t spoint, con
SetPosition( GetPosition() );
if ( Arena::GetInterface() ) {
+ std::string str(_n( "%{count} %{name} rises from the dead!", "%{count} %{name} rise from the dead!", %{count} ) );
StringReplace( str, "%{count}", resurrect );
StringReplace( str, "%{name}", GetName() );
Arena::GetInterface()->SetStatus( str, true ); |
codereview_new_cpp_data_4649 | void Battle::Unit::SpellRestoreAction( const Spell & spell, uint32_t spoint, con
SetPosition( GetPosition() );
if ( Arena::GetInterface() ) {
- std::string str(_n( "%{count} %{name} rises from the dead!", "%{count} %{name} rise from the dead!", %{count} ) );
StringReplace( str, "%{count}", resurrect );
StringReplace( str, "%{name}", GetName() );
Arena::GetInterface()->SetStatus( str, true );
:warning: **clang\-diagnostic\-error** :warning:
expected expression
void Battle::Unit::SpellRestoreAction( const Spell & spell, uint32_t spoint, con
SetPosition( GetPosition() );
if ( Arena::GetInterface() ) {
+ std::string str(_n( "%{count} %{name} rises from the dead!", "%{count} %{name} rise from the dead!", count ) );
StringReplace( str, "%{count}", resurrect );
StringReplace( str, "%{name}", GetName() );
Arena::GetInterface()->SetStatus( str, true ); |
codereview_new_cpp_data_4650 | void Castle::ActionNewWeek()
// population halved
if ( world.GetWeekType().GetType() == WeekName::PLAGUE ) {
- for ( size_t i = 0; i < CASTLEMAXMONSTER; ++i ) {
- dwelling[i] /= 2;
}
}
// Month Of
:warning: **modernize\-loop\-convert** :warning:
use range\-based for loop instead
```suggestion
for (unsigned int & i : dwelling) {
```
void Castle::ActionNewWeek()
// population halved
if ( world.GetWeekType().GetType() == WeekName::PLAGUE ) {
+ for ( uint32_t & dwellingRef : dwelling ) {
+ dwellingRef /= 2;
}
}
// Month Of |
codereview_new_cpp_data_4651 | void Castle::ActionNewWeek()
// population halved
if ( world.GetWeekType().GetType() == WeekName::PLAGUE ) {
- for ( size_t i = 0; i < CASTLEMAXMONSTER; ++i ) {
- dwelling[i] /= 2;
}
}
// Month Of
:warning: **modernize\-loop\-convert** :warning:
use range\-based for loop instead
```suggestion
i /= 2;
```
void Castle::ActionNewWeek()
// population halved
if ( world.GetWeekType().GetType() == WeekName::PLAGUE ) {
+ for ( uint32_t & dwellingRef : dwelling ) {
+ dwellingRef /= 2;
}
}
// Month Of |
codereview_new_cpp_data_4652 | 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
```
namespace fheroes2
icnVsSprite[75].setPosition( icnVsSprite[75].x(), icnVsSprite[75].y() );
updateSmallFontLetterShadow( icnVsSprite[75] );
}
}
} |
codereview_new_cpp_data_4653 | namespace
strengthLimit /= 2;
}
- // Do not even care about visiting this object as it brings no visible advantage.
return objectArmyStrength > rawArmyStrength * strengthLimit;
}
:warning: **bugprone\-easily\-swappable\-parameters** :warning:
2 adjacent parameters of `` HeroesValidObject `` of similar type \(`` const double ``\) are easily swapped by mistake
namespace
strengthLimit /= 2;
}
+ // Do not even care about this monster as it brings no visible advantage to the army.
return objectArmyStrength > rawArmyStrength * strengthLimit;
}
|
codereview_new_cpp_data_4654 | void Troops::addNewTroopsToFreeSlots( const Troop & troop, uint32_t maxSlots )
uint32_t remainingCount = troop.GetCount() % maxSlots;
uint32_t remainingSlots = maxSlots;
- auto TryCreateTroopChunk = [&remainingSlots, &remainingCount, chunk, troop]( Troop & newTroop ) {
if ( remainingSlots <= 0 )
return;
Despite the `troop` is itself a reference, it [will be captured by value](https://godbolt.org/z/hca6b9n44) here instead of reference. I believe this is not desirable here and capture should be replaced by `&troop`.
void Troops::addNewTroopsToFreeSlots( const Troop & troop, uint32_t maxSlots )
uint32_t remainingCount = troop.GetCount() % maxSlots;
uint32_t remainingSlots = maxSlots;
+ auto TryCreateTroopChunk = [&remainingSlots, &remainingCount, chunk, &troop]( Troop & newTroop ) {
if ( remainingSlots <= 0 )
return;
|
codereview_new_cpp_data_4842 | 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;
}
}
```suggestion
ELEKTRA_SET_RESOURCE_ERRORF (parentKey, "The mini storage Plugin doesn't support the meta key %s", pos);
```
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_4843 | 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;
}
}
Comment seems incomplete.
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_4844 | static void testwriteInvalidMetaMustFail (const char * file)
PLUGIN_OPEN ("csvstorage");
succeed_if (plugin->kdbSet (plugin, ks, parentKey) == ELEKTRA_PLUGIN_STATUS_ERROR,
"kdbSet did not error on invalid meta key insertion");
- ksDel (conf);
ksDel (ks);
keyDel (parentKey);
PLUGIN_CLOSE ();
Sorry, your solution was correct!
You used the macro `PLUGIN_OPEN(NAME)` which calls the function `elektraPluginOpen(...)` with the KeySet `conf` as argument.
https://github.com/ElektraInitiative/libelektra/blob/6a6d1bf57cc50348cbfbe9c94da7dc39c67969ad/tests/cframework/tests_plugin.h#L14-L22
There, the KeySet is assigned to an internal variable:
https://github.com/ElektraInitiative/libelektra/blob/6a6d1bf57cc50348cbfbe9c94da7dc39c67969ad/src/libs/elektra/plugin.c#L92
At the end of your test, the `PLUGIN_CLOSE()` macro is called and there `ksDel (handle->conf)` is done:
https://github.com/ElektraInitiative/libelektra/blob/6a6d1bf57cc50348cbfbe9c94da7dc39c67969ad/src/libs/elektra/plugin.c#L135
```suggestion
```
static void testwriteInvalidMetaMustFail (const char * file)
PLUGIN_OPEN ("csvstorage");
succeed_if (plugin->kdbSet (plugin, ks, parentKey) == ELEKTRA_PLUGIN_STATUS_ERROR,
"kdbSet did not error on invalid meta key insertion");
ksDel (ks);
keyDel (parentKey);
PLUGIN_CLOSE (); |
codereview_new_cpp_data_4845 | void test_desktop (void)
printf ("clear all variables to test \"no desktop\"\n");
clearenv ();
keys = ksNew (0, KS_END);
plugin->kdbGet (plugin, keys, parentKey);
Key const * emptyResult = ksLookupByName (keys, "user:/tests/desktop", 0);
You allocated a new `KeySet` without freeing the previously allocated one with `ksDel (keys)`.
```suggestion
ksDel (keys);
keys = ksNew (0, KS_END);
```
void test_desktop (void)
printf ("clear all variables to test \"no desktop\"\n");
clearenv ();
+ ksDel (keys);
keys = ksNew (0, KS_END);
plugin->kdbGet (plugin, keys, parentKey);
Key const * emptyResult = ksLookupByName (keys, "user:/tests/desktop", 0); |
codereview_new_cpp_data_5078 | static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) {
Py_XDECREF(self);
#endif
if (self_found) {
- // PyCFunction_New will create and own method reference, no need to worry about it
PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method);
Py_DECREF(method); // __Pyx_PyObject_GetAttrStr
if (unlikely(!unbound_method)) {
```suggestion
// New PyCFunction will own method reference
PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method);
Py_DECREF(method); // __Pyx_PyObject_GetAttrStr
```
static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) {
Py_XDECREF(self);
#endif
if (self_found) {
+ // 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)) { |
codereview_new_cpp_data_5079 | static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) {
Py_XDECREF(self);
#endif
if (self_found) {
- // 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
PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method);
if (unlikely(!unbound_method)) return -1;
// New PyCFunction will own method reference, thus decref __Pyx_PyObject_GetAttrStr
Py_DECREF(method);
```
static int __Pyx_TryUnpackUnboundCMethod(__Pyx_CachedCFunction* target) {
Py_XDECREF(self);
#endif
if (self_found) {
PyObject *unbound_method = PyCFunction_New(&__Pyx_UnboundCMethod_Def, method);
if (unlikely(!unbound_method)) return -1;
+ // New PyCFunction will own method reference, thus decref __Pyx_PyObject_GetAttrStr
+ Py_DECREF(method);
target->method = unbound_method;
}
} |
codereview_new_cpp_data_5080 | 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;
Seems worth using a vectorcall here, if available, rather than creating a new tuple just for the call. (Not sure if that's an optimisation that we need to do right now.)
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_5081 | static int __Pyx_main(int argc, wchar_t **argv)
PyConfig config;
PyConfig_InitPythonConfig(&config);
- /* Disable parsing command line arguments */
config.parse_argv = 0;
if (argc && argv) {
We generally exclude comments from the generated C files if they start with `//`. This comment seems worth excluding.
```suggestion
// Disable parsing command line arguments
```
static int __Pyx_main(int argc, wchar_t **argv)
PyConfig config;
PyConfig_InitPythonConfig(&config);
+ // Disable parsing command line arguments
config.parse_argv = 0;
if (argc && argv) { |
codereview_new_cpp_data_5093 |
#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)
This is probably worth picking to 0.29.x. I'm inclined not to pick the rest on the basis that we're largely trying not to change it.
#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) |
codereview_new_cpp_data_5101 | static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) {
return __Pyx_PyFunction_FastCall(func, NULL, 0);
}
#endif
-#ifdef __Pyx_CyFunction_USED && defined(NDEBUG)
// TODO PyCFunction_GET_FLAGS has a type-check assert that breaks with a CyFunction
// in debug mode. There is likely to be a better way of avoiding tripping this
// check that doesn't involve disabling the optimized path.
This is invalid syntax. How about:
```suggestion
#if defined(__Pyx_CyFunction_USED) && defined(NDEBUG)
```
static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) {
return __Pyx_PyFunction_FastCall(func, NULL, 0);
}
#endif
+#if defined(__Pyx_CyFunction_USED) && defined(NDEBUG)
// TODO PyCFunction_GET_FLAGS has a type-check assert that breaks with a CyFunction
// in debug mode. There is likely to be a better way of avoiding tripping this
// check that doesn't involve disabling the optimized path. |
codereview_new_cpp_data_5103 | static double __Pyx_SoftComplexToDouble(__pyx_t_double_complex value) {
// In Python the type would be determined right after the number is
// created (usually '**'), while here it's determined when coerced
// to a PyObject, which may be a few operations later.
- if (__Pyx_CIMAG(value)) {
PyErr_SetString(PyExc_TypeError,
"Cannot convert 'complex' with non-zero imaginary component to 'double' "
"(this most likely comes from the '**' operator; "
```suggestion
if (unlikely(__Pyx_CIMAG(value))) {
```
static double __Pyx_SoftComplexToDouble(__pyx_t_double_complex value) {
// In Python the type would be determined right after the number is
// created (usually '**'), while here it's determined when coerced
// to a PyObject, which may be a few operations later.
+ if (unlikely(__Pyx_CIMAG(value))) {
PyErr_SetString(PyExc_TypeError,
"Cannot convert 'complex' with non-zero imaginary component to 'double' "
"(this most likely comes from the '**' operator; " |
codereview_new_cpp_data_5111 |
#endif
#endif
-#if CYTHON_USE_MODULE_STATE && CYTHON_PEP489_MULTI_PHASE_INIT
-#error "Cannot combine CYTHON_USE_MODULE_STATE and CYTHON_PEP489_MULTI_PHASE_INIT"
-/* since PyState_FindModule requires that each module-def is linked to 1 (or 0) modules
-and multi-phase init allows the same module to be imported many times */
-#endif
-
#if !defined(CYTHON_FAST_PYCCALL)
#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1)
#endif
Should this really be a compile time error? The fact that is can be imported multiple times does not mean that it will be.
#endif
#endif
#if !defined(CYTHON_FAST_PYCCALL)
#define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1)
#endif |
codereview_new_cpp_data_5118 |
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#ifndef CYTHON_PEP489_MULTI_PHASE_INIT
- #define CYTHON_PEP489_MULTI_PHASE_INIT (PY_VERSION_HEX >= 0x03050000)
#endif
#ifndef CYTHON_USE_TP_FINALIZE
#define CYTHON_USE_TP_FINALIZE 1
Since that you say this is a fork on Python 3.9, I assume this can be
```suggestion
#define CYTHON_PEP489_MULTI_PHASE_INIT 1
```
#undef CYTHON_FAST_PYCALL
#define CYTHON_FAST_PYCALL 0
#ifndef CYTHON_PEP489_MULTI_PHASE_INIT
+ #define CYTHON_PEP489_MULTI_PHASE_INIT 1
#endif
#ifndef CYTHON_USE_TP_FINALIZE
#define CYTHON_USE_TP_FINALIZE 1 |
codereview_new_cpp_data_5121 | static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name,
// (most likely because alignof isn't available)
alignment = size % alignment;
}
- itemsize = itemsize > (Py_ssize_t)alignment ? itemsize : (Py_ssize_t)alignment;
}
if ((size_t)(basicsize + itemsize) < size) {
PyErr_Format(PyExc_ValueError,
```suggestion
if (itemsize < (Py_ssize_t)alignment)
itemsize = (Py_ssize_t)alignment;
```
static PyTypeObject *__Pyx_ImportType(PyObject *module, const char *module_name,
// (most likely because alignof isn't available)
alignment = size % alignment;
}
+ if (itemsize < (Py_ssize_t)alignment)
+ itemsize = (Py_ssize_t)alignment;
}
if ((size_t)(basicsize + itemsize) < size) {
PyErr_Format(PyExc_ValueError, |
codereview_new_cpp_data_5123 | static int __Pyx_MergeKeywords(PyObject *kwdict, PyObject *source_mapping) {
#if CYTHON_METH_FASTCALL
#define __Pyx_Arg_FASTCALL(args, i) args[i]
#define __Pyx_NumKwargs_FASTCALL(kwds) PyTuple_GET_SIZE(kwds)
- #define __Pyx_KwValues_FASTCALL(args, nargs) (args+nargs)
static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s);
#define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw)
#else
I know, the macro is never called on anything but plain variables, but it's cheap to add parentheses anyway and makes it safer to change the usage.
```suggestion
#define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs))
```
static int __Pyx_MergeKeywords(PyObject *kwdict, PyObject *source_mapping) {
#if CYTHON_METH_FASTCALL
#define __Pyx_Arg_FASTCALL(args, i) args[i]
#define __Pyx_NumKwargs_FASTCALL(kwds) PyTuple_GET_SIZE(kwds)
+ #define __Pyx_KwValues_FASTCALL(args, nargs) ((args) + (nargs))
static CYTHON_INLINE PyObject * __Pyx_GetKwValue_FASTCALL(PyObject *kwnames, PyObject *const *kwvalues, PyObject *s);
#define __Pyx_KwargsAsDict_FASTCALL(kw, kwvalues) _PyStack_AsDict(kwvalues, kw)
#else |
codereview_new_cpp_data_5127 | static void __pyx_fatalerror(const char *fmt, ...) Py_NO_RETURN {
va_list vargs;
char msg[200];
-
va_start(vargs, fmt);
vsnprintf(msg, 200, fmt, vargs);
va_end(vargs);
Just clearing up an extra blank line
```suggestion
```
static void __pyx_fatalerror(const char *fmt, ...) Py_NO_RETURN {
va_list vargs;
char msg[200];
va_start(vargs, fmt);
vsnprintf(msg, 200, fmt, vargs);
va_end(vargs); |
codereview_new_cpp_data_5128 |
* \warning This program is a poor implementation and does not utilize any of
* the C++ STL features.
*/
-#include <algorithm>
-#include <iostream>
-#include <queue>
using node = struct node {
int data;
Explain why each header is required
* \warning This program is a poor implementation and does not utilize any of
* the C++ STL features.
*/
+#include <algorithm> // for std::max
+#include <iostream> // for std::cout
+#include <queue> // for std::queue
using node = struct node {
int data; |
codereview_new_cpp_data_5129 |
* x. All this should be done in linear time
*
* @author [David Leal](https://github.com/Panquesito7)
- * @author Unknown author
*/
#include <algorithm> /// for std::is_sorted
Non-blocking; I think you can figure it out if you check out the commit `f22baf19210b17c8567d461ad35259322543701c` in your local - I don't have this repo cloned in my local env so can't do this. This was the parent commit before `ayankhan` made his changes to fix overflow issues, once you check that out you can do `git blame sorting/quick_sort.cpp` to check who wrote it 😄.
* x. All this should be done in linear time
*
* @author [David Leal](https://github.com/Panquesito7)
+ * @author [popoapp](https://github.com/popoapp)
*/
#include <algorithm> /// for std::is_sorted |
codereview_new_cpp_data_5130 | static void test() {
int main() {
test(); // run self-test implementations
return 0;
-}
\ No newline at end of file
Missing an endline. Without this endline, there could be issues with some IDEs and configurations.
```suggestion
}
```
static void test() {
int main() {
test(); // run self-test implementations
return 0;
\ No newline at end of file
+}
|
codereview_new_cpp_data_5131 |
* 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)
This is discouraged. Please strictly use `std::` for each `std` member.
* 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_5132 |
* 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)
Functions should be documented explaining the use of its parameters, a brief description, and what it returns.
* 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_5133 |
* 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)
Do not use C-style arrays. Instead, use `std::vector` or `std::array` accordingly.
* 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_5134 |
* [Geeks For Geeks](https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/)
*/
-#include <cassert> // for assert
-#include <iostream> // for IO operations
-#include <vector> // for vectors
-// using namespace std;
/**
```suggestion
#include <cassert> /// for assert
#include <iostream> /// for IO operations
#include <vector> /// for std::vector
```
* [Geeks For Geeks](https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/)
*/
+#include <cassert> /// for assert
+#include <iostream> /// for IO operations
+#include <vector> /// for std::vector
/** |
codereview_new_cpp_data_5135 |
* [Geeks For Geeks](https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/)
*/
-#include <cassert> // for assert
-#include <iostream> // for IO operations
-#include <vector> // for vectors
-// using namespace std;
/**
```suggestion
/**
* @namespace dynamic_programming
* @brief Dynamic Programming algorithms
*/
namespace dynamic_programming {
/**
```
* [Geeks For Geeks](https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/)
*/
+#include <cassert> /// for assert
+#include <iostream> /// for IO operations
+#include <vector> /// for std::vector
/** |
codereview_new_cpp_data_5136 | static void test() {
arr = {8, -8, 10, -9, 10, -11, 12};
assert(dynamic_programming::maxCircularSum(arr) == 23);
}
```suggestion
assert(dynamic_programming::maxCircularSum(arr) == 23);
std::cout << "All tests have successfully passed!\n";
```
static void test() {
arr = {8, -8, 10, -9, 10, -11, 12};
assert(dynamic_programming::maxCircularSum(arr) == 23);
+
+ std::cout << "All tests have successfully passed!\n";
}
|
codereview_new_cpp_data_5137 | int main()
std::cout << "\nEnter the size of the array [in range 1-30 ]: ";
std::cin >> size;
- while (size <= 0 || size > 30)
- {
- if (size <= 0)
- {
- std::cout << "Size cannot be less than zero. Please choose another value: ";
- std::cin >> size;
- }
- if (size > 30)
- {
- std::cout << "Size entered more than 30. Please choose a lower value: ";
- std::cin >> size;
- }
}
int *array = new int[size];
Hmm, I'm not sure what's the difference here. Could you explain the benefits, please?
int main()
std::cout << "\nEnter the size of the array [in range 1-30 ]: ";
std::cin >> size;
+ while (size <= 0 || size > 30){
+ std::cout << "Size can only be 1-30. Please choose another value: ";
+ std::cin >> size;
+ }
}
int *array = new int[size]; |
codereview_new_cpp_data_5138 | int main()
std::cout << "\nEnter the size of the array [in range 1-30 ]: ";
std::cin >> size;
- while (size <= 0 || size > 30)
- {
- if (size <= 0)
- {
- std::cout << "Size cannot be less than zero. Please choose another value: ";
- std::cin >> size;
- }
- if (size > 30)
- {
- std::cout << "Size entered more than 30. Please choose a lower value: ";
- std::cin >> size;
- }
}
int *array = new int[size];
I really feel code getting brittle. Can not we rethink? And we have to take input anyways so input can be taken anyways should not be in if block.
int main()
std::cout << "\nEnter the size of the array [in range 1-30 ]: ";
std::cin >> size;
+ while (size <= 0 || size > 30){
+ std::cout << "Size can only be 1-30. Please choose another value: ";
+ std::cin >> size;
+ }
}
int *array = new int[size]; |
codereview_new_cpp_data_5139 | int main()
std::cout << "\nEnter the size of the array [in range 1-30 ]: ";
std::cin >> size;
- while (size <= 0 || size > 30)
- {
- if (size <= 0)
- {
- std::cout << "Size cannot be less than zero. Please choose another value: ";
- std::cin >> size;
- }
- if (size > 30)
- {
- std::cout << "Size entered more than 30. Please choose a lower value: ";
- std::cin >> size;
- }
}
int *array = new int[size];
To make it shorter, we could do something like this. What do you think? 🙂
```suggestion
while (size <= 0 || size > 30){
std::cout << "Size can only be 1-30. Please choose another value: ";
std::cin >> size;
}
```
int main()
std::cout << "\nEnter the size of the array [in range 1-30 ]: ";
std::cin >> size;
+ while (size <= 0 || size > 30){
+ std::cout << "Size can only be 1-30. Please choose another value: ";
+ std::cin >> size;
+ }
}
int *array = new int[size]; |
codereview_new_cpp_data_5140 |
/**
- * @file median_search2.cpp
*
* @details
* Given a linked list L[0,....,n] of n numbers, find the middle node.
No need to add the filename. It's best to let Doxygen automatically detect it, otherwise, you'd have to specify the whole directory as well.
```suggestion
* @file
```
__
[](https://semasoftware.com/gh) **Summary:** :hammer_and_wrench: This code needs a fix
/**
+ * @file
*
* @details
* Given a linked list L[0,....,n] of n numbers, find the middle node. |
codereview_new_cpp_data_5141 |
* print median(B) #should be 4
*
* @author [Benjamin Weiss](https://github.com/weiss-ben)
*/
#include <cassert> /// for assert
This will help in the Doxygen documentation.
```suggestion
* @author [Benjamin Weiss](https://github.com/weiss-ben)
* @see median_search.cpp
```
* print median(B) #should be 4
*
* @author [Benjamin Weiss](https://github.com/weiss-ben)
+ * @see median_search.cpp
*/
#include <cassert> /// for assert |
codereview_new_cpp_data_5142 | static void test() {
assert(3 == median->val); // 3 is the value of the median node.
std::cout << "test case:1 passed\n";
- // Clean up
- while (head1) {
- ListNode* t = head1;
- head1 = head1->next;
- delete t;
- }
- delete head1;
- delete temp;
// Test case # 2
auto* head2 = new ListNode;
We're already freeing the `head1` memory twice here.
```suggestion
```
static void test() {
assert(3 == median->val); // 3 is the value of the median node.
std::cout << "test case:1 passed\n";
// Test case # 2
auto* head2 = new ListNode; |
codereview_new_cpp_data_5143 |
/**
* @file
- * @brief A generic [binary search tree](https://en.wikipedia.org/wiki/Binary_search_tree) implementation. (https://www.scaler.com/topics/data-structures/binary-search-tree/)
* @see binary_search_tree.cpp
*/
```suggestion
* @brief A generic [binary search tree](https://en.wikipedia.org/wiki/Binary_search_tree) implementation. Here you can find more information about the algorithm: [Scaler - Binary Search tree](https://www.scaler.com/topics/data-structures/binary-search-tree/)
```
/**
* @file
+ * @brief A generic [binary search tree](https://en.wikipedia.org/wiki/Binary_search_tree) implementation. Here you can find more information about the algorithm: [Scaler - Binary Search tree](https://www.scaler.com/topics/data-structures/binary-search-tree/)
* @see binary_search_tree.cpp
*/
|
codereview_new_cpp_data_5144 | template <typename TensorDataType>
bool hdf5_reader<TensorDataType>::fetch_datum(Mat& X, int data_id, int mb_idx) {
prof_region_begin("fetch_datum", prof_colors[0], false);
- assert_eq(sizeof(DataType) % sizeof(TensorDataType), 0ul);
assert_eq((unsigned long) X.Height(),
- m_num_features / dc::get_number_of_io_partitions());
- // / (sizeof(DataType) / sizeof(TensorDataType)));
- // FIXME (trb 02/03/2023) -- when DataType is 'float' and
- // TensorDataType is 'double', this last operand will be 0, which is
- // invalid.
auto X_v = create_datum_view(X, mb_idx);
if (m_use_data_store) {
Is this assert still valid with the last bit commented out?
template <typename TensorDataType>
bool hdf5_reader<TensorDataType>::fetch_datum(Mat& X, int data_id, int mb_idx) {
prof_region_begin("fetch_datum", prof_colors[0], false);
+ // Note (trb 02/06/2023): By making this a constexpr check, the
+ // compiler can deduce that the following "assert_eq" will not
+ // divide by zero in any surviving case. A necessary condition for
+ // sizeof(DataType) % sizeof(TensorDataType) == 0ul is that
+ // sizeof(DataType) >= sizeof(TensorDataType), so (sizeof(DataType)
+ // / sizeof(TensorDataType)) >= 1 in all surviving cases.
+ if constexpr (sizeof(DataType) % sizeof(TensorDataType) > 0ul) {
+ LBANN_ERROR("Invalid configuration.");
+ return false;
+ }
assert_eq((unsigned long) X.Height(),
+ m_num_features / dc::get_number_of_io_partitions()
+ / (sizeof(DataType) / sizeof(TensorDataType)));
auto X_v = create_datum_view(X, mb_idx);
if (m_use_data_store) { |
codereview_new_cpp_data_5145 |
#include "lbann/utils/protobuf/impl.hpp"
#include <google/protobuf/descriptor.h>
-#include "lbann/proto/protobuf_utils_test_messages.pb.h"
#include <string>
```suggestion
#include "protobuf_utils_test_messages.pb.h"
```
This is private-to-the-testing, so it does not need the same treatment.
#include "lbann/utils/protobuf/impl.hpp"
#include <google/protobuf/descriptor.h>
+#include "protobuf_utils_test_messages.pb.h"
#include <string>
|
codereview_new_cpp_data_5148 | void model::setup_distconv()
}
}
if (m_comm->am_world_master()) {
- std::cout << "\nDistconv-enabled layers:\n\t" << dc_enabled.str() << std::endl << std::endl;
- std::cout << "Distconv-disabled layers:\n\t" << dc_disabled.str() << std::endl;
- std::stringstream ss;
- print_parallel_strategy_header(ss);
- std::cout << "\nParallel Strategy description - " << ss.str() << std::endl;
}
setup_distributions();
print_distributions();
```suggestion
std::cout << "\nDistconv-enabled layers:\n\t" << dc_enabled.str() << "\n\n"
<< "Distconv-disabled layers:\n\t" << dc_disabled.str() << "\n\n"
<< "Parallel Strategy description - ";
print_parallel_strategy_header(std::cout);
endl(std::cout);
```
void model::setup_distconv()
}
}
if (m_comm->am_world_master()) {
+ std::cout << "\nDistconv-enabled layers:\n\t" << dc_enabled.str() << "\n\n"
+ << "Distconv-disabled layers:\n\t" << dc_disabled.str() << "\n\n"
+ << "Parallel Strategy description - ";
+ print_parallel_strategy_header(std::cout);
+ endl(std::cout);
}
setup_distributions();
print_distributions(); |
codereview_new_cpp_data_5153 | auto make_field_char_parser() {
return parsers::alnum | chr{'_'} | chr{'-'} | chr{':'};
}
auto make_extractor_parser() {
using namespace parser_literals;
// A field cannot start with:
```suggestion
// Creates a parser that returns an operand containing either a type or field extractor.
```
auto make_field_char_parser() {
return parsers::alnum | chr{'_'} | chr{'-'} | chr{':'};
}
+/// Creates a parser that returns an operand containing either a type or field extractor.
auto make_extractor_parser() {
using namespace parser_literals;
// A field cannot start with: |
codereview_new_cpp_data_5154 | TEST(parseable - custom type extractor predicate) {
REQUIRE(pred);
auto extractor = caf::get_if<type_extractor>(&pred->lhs);
REQUIRE(extractor);
CHECK_EQUAL(pred->op, relational_operator::not_equal);
CHECK_EQUAL(pred->rhs, predicate::operand{data{}});
}
One more check please.
```suggestion
REQUIRE(extractor);
auto expected = type{"foo.bar", type{}};
CHECK_EQUAL(extractor->type, expected);
```
TEST(parseable - custom type extractor predicate) {
REQUIRE(pred);
auto extractor = caf::get_if<type_extractor>(&pred->lhs);
REQUIRE(extractor);
+ auto expected = type{"foo.bar", type{}};
+ CHECK_EQUAL(extractor->type, expected);
CHECK_EQUAL(pred->op, relational_operator::not_equal);
CHECK_EQUAL(pred->rhs, predicate::operand{data{}});
} |
codereview_new_cpp_data_5155 | caf::error unpack(const fbs::Data& from, data& to) {
}
case fbs::data::Data::pattern: {
auto options = pattern_options{};
- options.case_insensitive
- = from.data_as_pattern()->options()->case_insensitive();
auto result = pattern::make(from.data_as_pattern()->value()->str(),
std::move(options));
if (!result)
This will crash when reading an old pattern that did not have this field set because you dereference a nullptr. Please never blindly do so, but rather put an assertion to indicate that you think as a dev that it cannot be a nullptr, or, well, check for it.
caf::error unpack(const fbs::Data& from, data& to) {
}
case fbs::data::Data::pattern: {
auto options = pattern_options{};
+ if (auto* unpacked_options = from.data_as_pattern()->options()) {
+ options.case_insensitive = unpacked_options->case_insensitive();
+ }
auto result = pattern::make(from.data_as_pattern()->value()->str(),
std::move(options));
if (!result) |
codereview_new_cpp_data_5156 | exporter(exporter_actor::stateful_pointer<exporter_state> self, expression expr,
: query_context::priority::normal;
VAST_DEBUG("spawned exporter with {} pipelines", pipelines.size());
self->state.pipeline = pipeline_executor{std::move(pipelines)};
self->state.index = std::move(index);
if (has_continuous_option(options)) {
if (self->state.pipeline.is_blocking()) {
Doesn't make sense to get results in batches in this case.
```suggestion
self->state.pipeline = pipeline_executor{std::move(pipelines)};
if (self->state.pipeline.is_blocking())
self->state.query_context.taste = std::numeric_limits<uint32_t>::max();
```
exporter(exporter_actor::stateful_pointer<exporter_state> self, expression expr,
: query_context::priority::normal;
VAST_DEBUG("spawned exporter with {} pipelines", pipelines.size());
self->state.pipeline = pipeline_executor{std::move(pipelines)};
+ // Always fetch all partitions for blocking pipelines.
+ if (self->state.pipeline.is_blocking())
+ self->state.query_context.taste = std::numeric_limits<uint32_t>::max();
self->state.index = std::move(index);
if (has_continuous_option(options)) {
if (self->state.pipeline.is_blocking()) { |
codereview_new_cpp_data_5157 | class plugin final : public virtual pipeline_operator_plugin {
for (const auto& [key, data] : parsed_assignments) {
fields_record[key] = data;
}
- config_record["fields"] = fields_record;
- auto config = configuration::make(config_record, false);
if (!config) {
return {
std::string_view{f, l},
std::move can be used here.
= std::move(fields_record)
I think it can also be used in the loop above but i think structured_bindings and std::move doesn't work that well so we can just ignore it as it isn't a hot path i guess.
class plugin final : public virtual pipeline_operator_plugin {
for (const auto& [key, data] : parsed_assignments) {
fields_record[key] = data;
}
+ config_record["fields"] = std::move(fields_record);
+ auto config = configuration::make(std::move(config_record), false);
if (!config) {
return {
std::string_view{f, l}, |
codereview_new_cpp_data_5158 | class plugin final : public virtual pipeline_operator_plugin {
};
}
auto config = configuration{};
- config.fields = parsed_extractors;
for (const auto& [key, value] : parsed_options) {
auto value_str = caf::get_if<std::string>(&value);
if (!value_str) {
we could move assign there = std::move(parsed_extractors)
class plugin final : public virtual pipeline_operator_plugin {
};
}
auto config = configuration{};
+ config.fields = std::move(parsed_extractors);
for (const auto& [key, value] : parsed_options) {
auto value_str = caf::get_if<std::string>(&value);
if (!value_str) { |
codereview_new_cpp_data_5159 | class plugin final : public virtual pipeline_operator_plugin {
for (const auto& [key, data] : parsed_assignments) {
fields_record[key] = data;
}
- config_record["fields"] = fields_record;
- auto config = configuration::make(config_record);
if (!config) {
return {
std::string_view{f, l},
This can be move assigned
class plugin final : public virtual pipeline_operator_plugin {
for (const auto& [key, data] : parsed_assignments) {
fields_record[key] = data;
}
+ config_record["fields"] = std::move(fields_record);
+ auto config = configuration::make(std::move(config_record));
if (!config) {
return {
std::string_view{f, l}, |
codereview_new_cpp_data_5160 | class plugin final : public virtual pipeline_operator_plugin {
if (!p(f, l, parsed_aggregations)) {
return {
std::string_view{f, l},
- caf::make_error(ec::syntax_error, fmt::format("failed to parse select "
"operator: '{}'",
pipeline)),
};
```suggestion
caf::make_error(ec::syntax_error, fmt::format("failed to parse summarize "
```
class plugin final : public virtual pipeline_operator_plugin {
if (!p(f, l, parsed_aggregations)) {
return {
std::string_view{f, l},
+ caf::make_error(ec::syntax_error, fmt::format("failed to parse summarize "
"operator: '{}'",
pipeline)),
}; |
codereview_new_cpp_data_5161 | store_plugin::make_store(system::accountant_actor accountant,
std::move(path), name());
}
-// -- pipeline_operator_plugin -------------------------------------------------
-
-std::pair<std::string_view, caf::expected<std::unique_ptr<pipeline_operator>>>
-pipeline_operator_plugin::make_pipeline_operator(
- std::string_view pipeline) const {
- // FIXME: Remove default impl.
- return {
- pipeline,
- caf::make_error(ec::unimplemented),
- };
-}
-
// -- plugin_ptr ---------------------------------------------------------------
caf::expected<plugin_ptr>
Can we have a story for this? Might forget about it in the future
store_plugin::make_store(system::accountant_actor accountant,
std::move(path), name());
}
// -- plugin_ptr ---------------------------------------------------------------
caf::expected<plugin_ptr> |
codereview_new_cpp_data_5162 | caf::expected<pipeline>
pipeline::parse(std::string name, std::string_view repr) {
auto result = pipeline{std::move(name), {}};
// plugin name parser
- using parsers::alnum, parsers::chr, parsers::space;
- const auto optional_ws = ignore(*space);
const auto plugin_name_char_parser = alnum | chr{'-'};
const auto plugin_name_parser = optional_ws >> +plugin_name_char_parser;
while (!repr.empty()) {
Should we use blank over space here?
caf::expected<pipeline>
pipeline::parse(std::string name, std::string_view repr) {
auto result = pipeline{std::move(name), {}};
// plugin name parser
+ using parsers::alnum, parsers::chr, parsers::blank;
+ const auto optional_ws = ignore(*blank);
const auto plugin_name_char_parser = alnum | chr{'-'};
const auto plugin_name_parser = optional_ws >> +plugin_name_char_parser;
while (!repr.empty()) { |
codereview_new_cpp_data_5163 |
#include "vast/error.hpp"
#include "vast/ids.hpp"
#include "vast/logger.hpp"
-#include "vast/pipeline_operator.hpp"
#include "vast/plugin.hpp"
#include "vast/query_context.hpp"
#include "vast/store.hpp"
Why do we need this include here?
#include "vast/error.hpp"
#include "vast/ids.hpp"
#include "vast/logger.hpp"
#include "vast/plugin.hpp"
#include "vast/query_context.hpp"
#include "vast/store.hpp" |
codereview_new_cpp_data_5164 | reader::read_impl(size_t max_events, size_t max_slice_size, consumer& f) {
// record batch.
if (read_result->batch->schema()->metadata()->FindKey("VAST:name:0")
== -1) {
- VAST_ERROR("{} skips record batch with {} rows: metadata is "
"incomaptible with VAST",
detail::pretty_type_name(*this),
read_result->batch->num_rows());
```suggestion
VAST_WARN("{} skips record batch with {} rows: metadata is "
```
The expected semantics for ERROR are that we fail.
reader::read_impl(size_t max_events, size_t max_slice_size, consumer& f) {
// record batch.
if (read_result->batch->schema()->metadata()->FindKey("VAST:name:0")
== -1) {
+ VAST_WARN("{} skips record batch with {} rows: metadata is "
"incomaptible with VAST",
detail::pretty_type_name(*this),
read_result->batch->num_rows()); |
codereview_new_cpp_data_5165 | active_partition_actor::behavior_type active_partition(
caf::get<record_type>(schema).leaves()) {
column_idx++;
// TODO: The qualified record field is a leftover from heterogeneous
- // partitions, the indexers can be indexed by the column instead.
const auto qf = qualified_record_field{schema, offset};
auto& idx = self->state.indexers[qf];
if (idx)
I think we should index them by offset instead of flat index, as we may want to create an index for a field in a record in a list, for example.
active_partition_actor::behavior_type active_partition(
caf::get<record_type>(schema).leaves()) {
column_idx++;
// TODO: The qualified record field is a leftover from heterogeneous
+ // partitions, the indexers can be indexed by the offset instead.
const auto qf = qualified_record_field{schema, offset};
auto& idx = self->state.indexers[qf];
if (idx) |
codereview_new_cpp_data_5166 | create_table_slice(const std::shared_ptr<arrow::RecordBatch>& record_batch,
auto fbs_ipc_buffer = flatbuffers::Offset<flatbuffers::Vector<uint8_t>>{};
if (serialize == table_slice::serialize::yes) {
auto ipc_ostream = arrow::io::BufferOutputStream::Create().ValueOrDie();
- auto opts = arrow::ipc::IpcWriteOptions::Defaults();
- opts.codec
- = arrow::util::Codec::Create(
- arrow::Compression::ZSTD,
- arrow::util::Codec::DefaultCompressionLevel(arrow::Compression::ZSTD)
- .ValueOrDie())
- .ValueOrDie();
auto stream_writer
- = arrow::ipc::MakeStreamWriter(ipc_ostream, record_batch->schema(), opts)
.ValueOrDie();
auto status = stream_writer->WriteRecordBatch(*record_batch);
if (!status.ok())
Maybe add a comment to make this configurable.
create_table_slice(const std::shared_ptr<arrow::RecordBatch>& record_batch,
auto fbs_ipc_buffer = flatbuffers::Offset<flatbuffers::Vector<uint8_t>>{};
if (serialize == table_slice::serialize::yes) {
auto ipc_ostream = arrow::io::BufferOutputStream::Create().ValueOrDie();
auto stream_writer
+ = arrow::ipc::MakeStreamWriter(ipc_ostream, record_batch->schema())
.ValueOrDie();
auto status = stream_writer->WriteRecordBatch(*record_batch);
if (!status.ok()) |
codereview_new_cpp_data_5169 | caf::error index_state::load_from_disk() {
caf::scoped_actor blocking{self->system()};
blocking->request(transformer, caf::infinite, atom::persist_v)
.receive(
- [&synopses, &stats, this](std::vector<partition_synopsis_pair> result) {
VAST_INFO("recovered {} corrupted partitions on startup",
result.size());
for (auto&& x : std::exchange(result, {})) {
Could this actually take lvalue ref? We don't need a copy here i believe
caf::error index_state::load_from_disk() {
caf::scoped_actor blocking{self->system()};
blocking->request(transformer, caf::infinite, atom::persist_v)
.receive(
+ [&synopses, &stats,
+ this](std::vector<partition_synopsis_pair>& result) {
VAST_INFO("recovered {} corrupted partitions on startup",
result.size());
for (auto&& x : std::exchange(result, {})) { |
codereview_new_cpp_data_5170 | caf::message pivot_command(const invocation& inv, caf::actor_system& sys) {
= spawn_or_connect_to_node(self, inv.options, content(sys.config()));
if (auto err = std::get_if<caf::error>(&node_opt))
return caf::make_message(std::move(*err));
- auto local_node = !std::holds_alternative<node_actor>(node_opt);
- const auto& node = local_node
- ? std::get<scope_linked<node_actor>>(node_opt).get()
- : std::get<node_actor>(node_opt);
VAST_ASSERT(node != nullptr);
- if (local_node) {
- // Register as the termination handler.
- auto signal_reflector
- = sys.registry().get<signal_reflector_actor>("signal-reflector");
- self->send(signal_reflector, atom::subscribe_v);
- }
// Spawn exporter at the node.
auto spawn_exporter = invocation{inv.options, "spawn exporter", {*query}};
VAST_DEBUG("{} spawns exporter with parameters: {}", inv, spawn_exporter);
This same pattern is now in most places that use `spawn_node` or `spawn_or_connect_to_node`. Should it just be `spawn_node` that sets this up instead, requiring `self` to be a `termination_handler_actor`? I think that would make this a lot less error prone, e.g., you forgot about `flush`, `rebuild`, `show`, and `web server` here (arguably `flush` should just use `connect_to_node`).
caf::message pivot_command(const invocation& inv, caf::actor_system& sys) {
= spawn_or_connect_to_node(self, inv.options, content(sys.config()));
if (auto err = std::get_if<caf::error>(&node_opt))
return caf::make_message(std::move(*err));
+ const auto& node = std::holds_alternative<node_actor>(node_opt)
+ ? std::get<node_actor>(node_opt)
+ : std::get<scope_linked<node_actor>>(node_opt).get();
VAST_ASSERT(node != nullptr);
// Spawn exporter at the node.
auto spawn_exporter = invocation{inv.options, "spawn exporter", {*query}};
VAST_DEBUG("{} spawns exporter with parameters: {}", inv, spawn_exporter); |
codereview_new_cpp_data_5171 | int main(int argc, char** argv) {
auto signal_monitoring_thread = std::thread([&] {
int signum = 0;
sigwait(&sigset, &signum);
- VAST_WARN("received signal {}", signum);
if (!stop)
caf::anon_send<caf::message_priority::high>(
reflector.get(), atom::internal_v, atom::signal_v, signum);
```suggestion
VAST_DEBUG("received signal {}", signum);
```
int main(int argc, char** argv) {
auto signal_monitoring_thread = std::thread([&] {
int signum = 0;
sigwait(&sigset, &signum);
+ VAST_DEBUG("received signal {}", signum);
if (!stop)
caf::anon_send<caf::message_priority::high>(
reflector.get(), atom::internal_v, atom::signal_v, signum); |
codereview_new_cpp_data_5172 | index(index_actor::stateful_pointer<index_state> self,
"partition transforms are not supported for the "
"global archive");
std::erase_if(old_partitions_per_type, [&](const auto& entry) {
- const auto& [id, type] = entry;
if (self->state.persisted_partitions.contains(id)) {
return false;
}
```suggestion
const auto& [id, _] = entry;
```
`type` is not accessed in this scope, you can use `_` to signal to the reader that we only care about the `id`.
I'm aware that this doesn't have special support in C++ and only works with one variable, but it is still better than creating a plot thread that is never resolved.
index(index_actor::stateful_pointer<index_state> self,
"partition transforms are not supported for the "
"global archive");
std::erase_if(old_partitions_per_type, [&](const auto& entry) {
+ const auto& [id, _] = entry;
if (self->state.persisted_partitions.contains(id)) {
return false;
} |
codereview_new_cpp_data_5173 | namespace {
constexpr size_t num_partitions = 4;
constexpr size_t num_events_per_parttion = 25;
-constexpr size_t taste_count = 4;
-constexpr size_t num_query_supervisors = 1;
const vast::time epoch;
These 2 variables should not be necessary any more.
namespace {
constexpr size_t num_partitions = 4;
constexpr size_t num_events_per_parttion = 25;
const vast::time epoch;
|
codereview_new_cpp_data_5174 | filter(const table_slice& slice, expression expr, const ids& hints) {
VAST_ASSERT(ret);
}
}
- VAST_ASSERT(builder->rows() != 0);
- VAST_ASSERT(builder->rows() != slice.rows());
auto new_slice = builder->finish();
new_slice.import_time(slice.import_time());
VAST_ASSERT(new_slice.encoding() != table_slice_encoding::none);
```suggestion
VAST_ASSERT_CHEAP(builder->rows() != 0);
VAST_ASSERT_CHEAP(builder->rows() != slice.rows());
```
filter(const table_slice& slice, expression expr, const ids& hints) {
VAST_ASSERT(ret);
}
}
+ VAST_ASSERT_CHEAP(builder->rows() != 0);
+ VAST_ASSERT_CHEAP(builder->rows() != slice.rows());
auto new_slice = builder->finish();
new_slice.import_time(slice.import_time());
VAST_ASSERT(new_slice.encoding() != table_slice_encoding::none); |
codereview_new_cpp_data_5175 |
namespace vast {
namespace {
inline uint32_t bitmask32(size_t bottom_bits) {
return bottom_bits >= 32 ? 0xffffffff : ((uint32_t{1} << bottom_bits) - 1);
}
```suggestion
inline uint32_t bitmask32(size_t bottom_bits) {
```
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_5176 | class address_encryptor {
private:
static constexpr inline auto msb_of_byte_mask = 0b10000000;
- EVP_CIPHER_CTX* ctx_;
- const EVP_CIPHER* cipher_;
- int block_size_;
- std::vector<address::byte_type> pad_;
std::vector<address::byte_type>
generate_one_time_pad(std::span<address::byte_type> bytes_to_encrypt) {
```suggestion
EVP_CIPHER_CTX* ctx_ = {};
const EVP_CIPHER* cipher_ {};
int block_size_ = {};
std::vector<address::byte_type> pad_ = {};
```
Even though it's not strictly needed for the vector, it is very much a good habit to get into for all member variables. The first three are trivially constructible and may as such contain garbage values if you don't explicitly initialize them.
class address_encryptor {
private:
static constexpr inline auto msb_of_byte_mask = 0b10000000;
+ EVP_CIPHER_CTX* ctx_ = {};
+ const EVP_CIPHER* cipher_ = {};
+ int block_size_ = {};
+ std::vector<address::byte_type> pad_ = {};
std::vector<address::byte_type>
generate_one_time_pad(std::span<address::byte_type> bytes_to_encrypt) { |
codereview_new_cpp_data_5177 | class pseudonymize_operator : public pipeline_operator {
for (const auto& field_name : config_.fields) {
for (const auto& index : caf::get<record_type>(layout).resolve_key_suffix(
field_name, layout.name())) {
- if (!caf::holds_alternative<address_type>(
- caf::get<record_type>(layout).field(index).type)) {
- VAST_ASSERT(false, "record batch field to be pseudonymized but does "
- "not "
- "have address type");
- VAST_WARN(fmt::format("Field {} is to be pseudonymized but does not "
- "contain "
- "IP "
- "address values; skipping pseudonymization",
- field_name));
continue;
}
transformations.push_back({index, std::move(transformation)});
I think this can just be a debug message; it's not worth of a warning, and it's certainly not something that should trigger an assertion.
The `VAST_*` family of macros also already do the formatting for you, so there's no need to call `fmt::format` youself.
For log messages, please adhere to noun-verb-object order, e.g., `VAST_DEBUG("pseudonymize operator skips field '{}' of unsupported type '{}'", ...)`.
class pseudonymize_operator : public pipeline_operator {
for (const auto& field_name : config_.fields) {
for (const auto& index : caf::get<record_type>(layout).resolve_key_suffix(
field_name, layout.name())) {
+ auto index_type = caf::get<record_type>(layout).field(index).type;
+ if (!caf::holds_alternative<address_type>(index_type)) {
+ VAST_DEBUG("pseudonymize operator skips field '{}' of unsupported "
+ "type '{}'",
+ field_name, index_type.name());
continue;
}
transformations.push_back({index, std::move(transformation)}); |
codereview_new_cpp_data_5178 | void ship_results(exporter_actor::stateful_pointer<exporter_state> self) {
return;
}
for (auto& t : *transformed)
- self->anon_send(st.sink, std::move(t));
}
}
One of the receivers depends on knowin who the sender is. In CAF 0.17.6 the anon_send didn't work properly and the sender was available. In CAF 0.18.6 the sender is nullptr so the code stopped working.
void ship_results(exporter_actor::stateful_pointer<exporter_state> self) {
return;
}
for (auto& t : *transformed)
+ self->request(st.sink, caf::infinite, std::move(t))
+ .then([] {},
+ [self, sink = st.sink](const caf::error& e) {
+ VAST_WARN("request from exporter: {} to sink: {} failed {}",
+ *self, sink, e);
+ });
}
}
|
codereview_new_cpp_data_5179 | status_handler(status_handler_actor::stateful_pointer<status_handler_state> self
return;
}
std::string result;
- caf::message_handler{[&](std::string& str) {
- result = std::move(str);
- }}(e.context());
rsp->append(result);
});
},
This must be somehow encoded as message inside message for no good reason. I can probably dig deeper into that and resolve the nested message reply here
status_handler(status_handler_actor::stateful_pointer<status_handler_state> self
return;
}
std::string result;
+ auto ctx = e.context();
+ caf::message_handler{[&](caf::message& msg) {
+ caf::message_handler{[&](std::string& str) {
+ result = std::move(str);
+ }}(msg);
+ }}(ctx);
rsp->append(result);
});
}, |
codereview_new_cpp_data_5180 | print_segment_contents(indentation&, const options&, vast::chunk_ptr chunk) {
auto writer = vast::format::json::writer{
std::make_unique<std::stringstream>(), settings};
for (const auto& slice : *segment)
- writer.write(slice);
writer.flush();
auto& out = static_cast<std::stringstream&>(writer.out());
fmt::print("{}\n", out.str());
We probably want to `exit(1)` here if printing failed.
I propose changing the error message like this:
```cpp
fmt::print(stderr, "!! failed to write segment slice: {}", err);
```
print_segment_contents(indentation&, const options&, vast::chunk_ptr chunk) {
auto writer = vast::format::json::writer{
std::make_unique<std::stringstream>(), settings};
for (const auto& slice : *segment)
+ if (auto err = writer.write(slice)) {
+ fmt::print(stderr, "!! failed to write segment slice: {}", err);
+ exit(1);
+ }
writer.flush();
auto& out = static_cast<std::stringstream&>(writer.out());
fmt::print("{}\n", out.str()); |
codereview_new_cpp_data_5181 | active_local_store(local_store_actor::stateful_pointer<active_store_state> self,
if (!slices)
return slices.error();
self->state.builder->reset(id);
- for (auto&& slice : std::exchange(*slices, {}))
- self->state.builder->add(std::move(slice));
return rank(self->state.builder->ids());
},
// store builder
Since we will remove this soon anyways (once we bump the minimum partition version to 1) I think ignoring the error here is fine, unlike in other places.
active_local_store(local_store_actor::stateful_pointer<active_store_state> self,
if (!slices)
return slices.error();
self->state.builder->reset(id);
+ for (auto&& slice : std::exchange(*slices, {})) [[maybe_unused]]
+ auto err = self->state.builder->add(std::move(slice));
return rank(self->state.builder->ids());
},
// store builder |
codereview_new_cpp_data_5182 | TEST(token validation) {
auto serialized_state = state.save();
REQUIRE_NOERROR(serialized_state);
vast::plugins::web::authenticator_state recovered_state;
- recovered_state.initialize_from(*serialized_state);
CHECK_EQUAL(state.authenticate(*token), true);
CHECK_EQUAL(state.authenticate("Yog-Sothoth"), false);
}
Should this be a `CHECK_EQUAL(..., caf::error{})` instead so you can actually see what error it was in case one is returned?
TEST(token validation) {
auto serialized_state = state.save();
REQUIRE_NOERROR(serialized_state);
vast::plugins::web::authenticator_state recovered_state;
+ CHECK_EQUAL(recovered_state.initialize_from(*serialized_state), caf::error{});
CHECK_EQUAL(state.authenticate(*token), true);
CHECK_EQUAL(state.authenticate("Yog-Sothoth"), false);
} |
codereview_new_cpp_data_5183 | inhale<format::json::reader>(const char* filename,
caf::put(settings, "vast.import.json.selector", "event_type:suricata");
auto input = std::make_unique<std::ifstream>(filename);
format::json::reader reader{settings, std::move(input)};
- reader.module(events::suricata_module);
return extract(reader, slice_size);
}
This should compare against `caf::error{}` so the error is shown if there is one. It should also be `REQUIRE_*` rather than `CHECK_*` as it doesn't make sense to continue test execution if this fails.
inhale<format::json::reader>(const char* filename,
caf::put(settings, "vast.import.json.selector", "event_type:suricata");
auto input = std::make_unique<std::ifstream>(filename);
format::json::reader reader{settings, std::move(input)};
+ REQUIRE_EQUAL(reader.module(events::suricata_module), caf::error{});
return extract(reader, slice_size);
}
|
codereview_new_cpp_data_5184 | segment::copy_without(const vast::segment& segment, const vast::ids& xs) {
if (!slices)
return slices.error();
for (auto&& slice : std::exchange(*slices, {}))
- builder.add(std::move(slice));
return builder.finish();
}
If this fails we should return the error from the function.
segment::copy_without(const vast::segment& segment, const vast::ids& xs) {
if (!slices)
return slices.error();
for (auto&& slice : std::exchange(*slices, {}))
+ if (auto err = builder.add(std::move(slice)))
+ return err;
return builder.finish();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.