Centralize counter API with server-side bounds and no-op filtering (#6879)

* Refactor server counter API to own overflow protection and filter no-op events

  Counter modifications now clamp to int bounds server-side and return change
  status, allowing command handlers to skip network broadcasts when values
  don't actually change.

* Centralize MAX_COUNTERS_ON_CARD and enforce [0, 999] bounds on server

  - Move MAX_COUNTERS_ON_CARD to trice_limits.h
  - Server clamps values in setCounter() and incrementCounter()
  - Client uses clamped comparison to allow recovery from invalid states
  - Add tests for clamping behavior

* move incrementCount() implementation from header to cpp
This commit is contained in:
DawnFire42 2026-05-21 23:39:35 -04:00 committed by GitHub
parent 74102aa1ec
commit 8dca14933c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 432 additions and 32 deletions

View file

@ -12,6 +12,7 @@
#include "card_state.h"
#include <libcockatrice/network/server/remote/game/server_card.h>
#include <libcockatrice/utility/trice_limits.h>
class CardDatabase;
class CardDragItem;
@ -21,7 +22,6 @@ class PlayerLogic;
class QAction;
class QColor;
const int MAX_COUNTERS_ON_CARD = 999;
const int ROTATION_DEGREES_PER_FRAME = 10;
class CardItem : public AbstractCardItem

View file

@ -1501,7 +1501,10 @@ void PlayerActions::offsetCardCounter(int counterId, int offset)
int oldValue = card->getCounters().value(counterId, 0);
int newValue = oldValue + offset;
if (newValue >= 0 && newValue <= MAX_COUNTERS_ON_CARD) {
// Early exit optimization: server enforces [0, MAX_COUNTERS_ON_CARD].
// Compare clamped value to allow recovery from invalid states.
int clampedValue = qBound(0, newValue, MAX_COUNTERS_ON_CARD);
if (clampedValue != oldValue) {
auto *cmd = new Command_SetCardCounter;
cmd->set_zone(card->getZone()->getName().toStdString());
cmd->set_card_id(card->getId());
@ -1541,7 +1544,9 @@ void PlayerActions::actSetCardCounter(int counterId)
for (auto card : sel) {
int oldValue = card->getCounters().value(counterId, 0);
Expression exp(oldValue);
int number = static_cast<int>(exp.parse(dialog.textValue()));
double parsed = exp.parse(dialog.textValue());
// Clamp in double precision first to avoid UB, then cast
int number = static_cast<int>(qBound(0.0, parsed, static_cast<double>(MAX_COUNTERS_ON_CARD)));
auto *cmd = new Command_SetCardCounter;
cmd->set_zone(card->getZone()->getName().toStdString());