id
stringlengths
27
29
content
stringlengths
226
3.24k
codereview_new_cpp_data_5185
disk_monitor(disk_monitor_actor::stateful_pointer<disk_monitor_state> self, } VAST_VERBOSE("{} checks db-directory of size {}", *self, *size); if (*size > self->state.config.high_water_mark) { - // TODO: Remove the static_cast when switching to CAF 0.18. self ->request(static_cast<disk_monitor_actor>(self), caf::infinite, atom::erase_v) Is that static cast still necessary? I thought that'd be fixed :( disk_monitor(disk_monitor_actor::stateful_pointer<disk_monitor_state> self, } VAST_VERBOSE("{} checks db-directory of size {}", *self, *size); if (*size > self->state.config.high_water_mark) { self ->request(static_cast<disk_monitor_actor>(self), caf::infinite, atom::erase_v)
codereview_new_cpp_data_5186
struct fixture { auto [root, _] = system::make_application(argv[0]); REQUIRE(root); // Parse the CLI. - cfg.command_line = ::sanitize_arguments(*root, cfg.command_line.begin(), - cfg.command_line.end()); auto invocation = ::parse(*root, cfg.command_line.begin(), cfg.command_line.end()); REQUIRE_NOERROR(invocation); Is there a reason why sanitizing the arguments is not part of the call to parse? struct fixture { auto [root, _] = system::make_application(argv[0]); REQUIRE(root); // Parse the CLI. auto invocation = ::parse(*root, cfg.command_line.begin(), cfg.command_line.end()); REQUIRE_NOERROR(invocation);
codereview_new_cpp_data_5187
catalog(catalog_actor::stateful_pointer<catalog_state> self, r.data.reserve(num_partitions_and_events_per_schema_and_version.size()); for (const auto& [schema_and_version, num_partitions_and_events] : num_partitions_and_events_per_schema_and_version) { - auto schema_num_partitions = num_partitions_and_events.first; - auto schema_num_events = num_partitions_and_events.second; total_num_partitions += schema_num_partitions; total_num_events += schema_num_events; r.data.push_back(data_point{ Could be changed to one liner: auto [num_partitions, num_events] = num_partitions_and_events; But tbh it's not a big deal. Pick the one you like more :) catalog(catalog_actor::stateful_pointer<catalog_state> self, r.data.reserve(num_partitions_and_events_per_schema_and_version.size()); for (const auto& [schema_and_version, num_partitions_and_events] : num_partitions_and_events_per_schema_and_version) { + auto [schema_num_partitions, schema_num_events] = num_partitions_and_events; total_num_partitions += schema_num_partitions; total_num_events += schema_num_events; r.data.push_back(data_point{
codereview_new_cpp_data_5188
auto test_schema = record_type{ auto test_layout2 = record_type{ {"struct", record_type{ - {"foo", type{string_type{}, {type::attribute_view{"required"}}}}, {"bar", string_type{}} }}}; ```suggestion {"foo", type{string_type{}, {{"required"}}}}, ``` auto test_schema = record_type{ auto test_layout2 = record_type{ {"struct", record_type{ + {"foo", type{string_type{}, {{"required"}}}}, {"bar", string_type{}} }}};
codereview_new_cpp_data_5189
caf::error make_blocking(int fd) { } caf::expected<bool> rpoll(int fd, int usec) { - fd_set rdset; - FD_ZERO(&rdset); - FD_SET(fd, &rdset); timeval timeout{0, usec}; - auto rc = ::select(fd + 1, &rdset, nullptr, nullptr, &timeout); if (rc < 0) return caf::make_error(ec::filesystem_error, "failed in select(2):", std::strerror(errno)); - return !!FD_ISSET(fd, &rdset); } caf::expected<bool> wpoll(int fd, int usec) { Can you call this `read_set` so that the implementation is symmetric to the `write_set` you introduced below? caf::error make_blocking(int fd) { } caf::expected<bool> rpoll(int fd, int usec) { + fd_set read_set; + FD_ZERO(&read_set); + FD_SET(fd, &read_set); timeval timeout{0, usec}; + auto rc = ::select(fd + 1, &read_set, nullptr, nullptr, &timeout); if (rc < 0) return caf::make_error(ec::filesystem_error, "failed in select(2):", std::strerror(errno)); + return !!FD_ISSET(fd, &read_set); } caf::expected<bool> wpoll(int fd, int usec) {
codereview_new_cpp_data_5190
struct accountant_state_impl { /// Handle to the uds output channel. std::unique_ptr<detail::uds_datagram_sender> uds_datagram_sink = nullptr; - /// Handle to the uds output channel is currently dropping it's input. bool uds_datagram_sink_dropping = false; /// The configuration. ```suggestion /// Handle to the UDS output channel is currently dropping its input. ``` struct accountant_state_impl { /// Handle to the uds output channel. std::unique_ptr<detail::uds_datagram_sender> uds_datagram_sink = nullptr; + /// Handle to the UDS output channel is currently dropping its input. bool uds_datagram_sink_dropping = false; /// The configuration.
codereview_new_cpp_data_5191
struct accountant_state_impl { auto buf = to_json_line(actor_id, ts, key, x, meta1, meta2); // Only poll the socket for write readiness if it did not drop the previous // line. Not doing this could increase the average message processing time - // of the accountant by timeout value, and just as with any actor, receiving - // messages at a higher frequency that they can be processed will eventually - // consume all available memory. - // The initial timeout of 1 second is somewhat arbitrary. Long enough so - // any re-initialization of the listening side would not incur data loss - // without being excessive. auto timeout_usec = uds_datagram_sink_dropping ? 0 : 1'000'000; auto delivered = dest.send( std::span<char>{reinterpret_cast<char*>(buf.data()), buf.size()}, ```suggestion // of the accountant by the timeout value, and just as with any actor, receiving ``` struct accountant_state_impl { auto buf = to_json_line(actor_id, ts, key, x, meta1, meta2); // Only poll the socket for write readiness if it did not drop the previous // line. Not doing this could increase the average message processing time + // of the accountant by the timeout value, and just as with any actor, + // receiving messages at a higher frequency that they can be processed will + // eventually consume all available memory. The initial timeout of 1 second + // is somewhat arbitrary. Long enough so any re-initialization of the + // listening side would not incur data loss without being excessive. auto timeout_usec = uds_datagram_sink_dropping ? 0 : 1'000'000; auto delivered = dest.send( std::span<char>{reinterpret_cast<char*>(buf.data()), buf.size()},
codereview_new_cpp_data_5192
uds_datagram_sender::make(const std::string& path) { caf::expected<bool> uds_datagram_sender::send(std::span<char> data, int timeout_usec) { - if (timeout_usec) { auto ready = wpoll(src_fd, timeout_usec); if (!ready) return ready.error(); ```suggestion if (timeout_usec > 0) { ``` uds_datagram_sender::make(const std::string& path) { caf::expected<bool> uds_datagram_sender::send(std::span<char> data, int timeout_usec) { + if (timeout_usec > 0) { auto ready = wpoll(src_fd, timeout_usec); if (!ready) return ready.error();
codereview_new_cpp_data_5193
struct rebuilder_state { detail::narrow_cast<int64_t>(desired_batch_size))); } emit_telemetry(); - // Newer partitions are more likely to contain undersized batches, so in the - // interest of letting rebatching for the rebuild of the current set of - // partitions not have to rebatch anything for as long as possible we sort - // the partitions for the current run by time ascending before sending them - // off. std::sort(current_run_partitions.begin(), current_run_partitions.end(), [](const partition_info& lhs, const partition_info& rhs) { return lhs.max_import_time < rhs.max_import_time; I had to read that comment multiple times before I started to understand what it is trying to say. How about rephrasing to: ```suggestion // We sort the selected partitions from old to new so the rebuild transform // sees the batches (and events) in the order they arrived. This prevents // the rebatching from shuffling events, and rebatching of already correctly // sized batches just for the right alignment. ``` struct rebuilder_state { detail::narrow_cast<int64_t>(desired_batch_size))); } emit_telemetry(); + // We sort the selected partitions from old to new so the rebuild transform + // sees the batches (and events) in the order they arrived. This prevents + // the rebatching from shuffling events, and rebatching of already correctly + // sized batches just for the right alignment. std::sort(current_run_partitions.begin(), current_run_partitions.end(), [](const partition_info& lhs, const partition_info& rhs) { return lhs.max_import_time < rhs.max_import_time;
codereview_new_cpp_data_5194
caf::expected<caf::actor> spawn_catalog(node_actor::stateful_pointer<node_state> self, spawn_arguments& args) { auto [accountant] = self->state.registry.find<accountant_actor>(); - auto detached = get_or(args.inv.options, "vast.catalog-detached", true); auto handle = detached ? self->spawn<caf::detached>(catalog, accountant) : self->spawn(catalog, accountant); return caf::actor_cast<caf::actor>(handle); We have the same issue for the filesystem actor, which is spawned by the node. We've decided to move this into a more generic "vast.disable-component-threads" (or similar) option with a fat warning above it in the example config. The option then also should be added to the root command in application.cpp. caf::expected<caf::actor> spawn_catalog(node_actor::stateful_pointer<node_state> self, spawn_arguments& args) { auto [accountant] = self->state.registry.find<accountant_actor>(); + auto detached = caf::get_or(args.inv.options, "vast.detach-components", + defaults::system::detach_components); auto handle = detached ? self->spawn<caf::detached>(catalog, accountant) : self->spawn(catalog, accountant); return caf::actor_cast<caf::actor>(handle);
codereview_new_cpp_data_5195
partition_actor::behavior_type passive_partition( msg.reason); return; } - VAST_ERROR("{} cannot reach its {} store and shuts down: {}", *self, self->state.store_id, msg.reason); self->quit(msg.reason); }); The grammar sounds a bit off, I suggest `{} shuts down after DOWN from store {}: {}"`. partition_actor::behavior_type passive_partition( msg.reason); return; } + VAST_ERROR("{} shuts down after DOWN from {} store: {}", *self, self->state.store_id, msg.reason); self->quit(msg.reason); });
codereview_new_cpp_data_5199
system::filesystem_actor::behavior_type mock_filesystem( }, [](vast::atom::move, const std::filesystem::path&, const std::filesystem::path&) -> caf::result<vast::atom::done> { - vast::die("not implemented"); }, []( vast::atom::move, const std::vector<std::pair<std::filesystem::path, std::filesystem::path>>&) -> caf::result<vast::atom::done> { - vast::die("not implemented"); }, [self](atom::mmap, const std::filesystem::path&) -> caf::result<chunk_ptr> { return self->make_response_promise<chunk_ptr>(); ```suggestion FAIL("not implemented"); ``` system::filesystem_actor::behavior_type mock_filesystem( }, [](vast::atom::move, const std::filesystem::path&, const std::filesystem::path&) -> caf::result<vast::atom::done> { + FAIL("not implemented"); }, []( vast::atom::move, const std::vector<std::pair<std::filesystem::path, std::filesystem::path>>&) -> caf::result<vast::atom::done> { + FAIL("not implemented"); }, [self](atom::mmap, const std::filesystem::path&) -> caf::result<chunk_ptr> { return self->make_response_promise<chunk_ptr>();
codereview_new_cpp_data_5200
system::filesystem_actor::behavior_type mock_filesystem( }, [](vast::atom::move, const std::filesystem::path&, const std::filesystem::path&) -> caf::result<vast::atom::done> { - vast::die("not implemented"); }, []( vast::atom::move, const std::vector<std::pair<std::filesystem::path, std::filesystem::path>>&) -> caf::result<vast::atom::done> { - vast::die("not implemented"); }, [self](atom::mmap, const std::filesystem::path&) -> caf::result<chunk_ptr> { return self->make_response_promise<chunk_ptr>(); ```suggestion FAIL("not implemented"); ``` system::filesystem_actor::behavior_type mock_filesystem( }, [](vast::atom::move, const std::filesystem::path&, const std::filesystem::path&) -> caf::result<vast::atom::done> { + FAIL("not implemented"); }, []( vast::atom::move, const std::vector<std::pair<std::filesystem::path, std::filesystem::path>>&) -> caf::result<vast::atom::done> { + FAIL("not implemented"); }, [self](atom::mmap, const std::filesystem::path&) -> caf::result<chunk_ptr> { return self->make_response_promise<chunk_ptr>();
codereview_new_cpp_data_5201
caf::error segment_builder::add(table_slice x) { if (x.offset() < min_table_slice_offset_) return caf::make_error(ec::unspecified, "slice offsets not increasing"); if (!x.is_serialized()) { - auto serialized_x = table_slice{to_record_batch(x), true}; serialized_x.import_time(x.import_time()); serialized_x.offset(x.offset()); x = std::move(serialized_x); That's a bit much right after the logic to serialize. ```suggestion ``` caf::error segment_builder::add(table_slice x) { if (x.offset() < min_table_slice_offset_) return caf::make_error(ec::unspecified, "slice offsets not increasing"); if (!x.is_serialized()) { + auto serialized_x + = table_slice{to_record_batch(x), table_slice::serialize::yes}; serialized_x.import_time(x.import_time()); serialized_x.offset(x.offset()); x = std::move(serialized_x);
codereview_new_cpp_data_5202
caf::error index_state::load_from_disk() { VAST_WARN("{} failed to remove partition file {} after recovery: {}", index, part_path, err); for (auto slice : *seg) - co_yield slice; } }(self, std::move(oversized_partitions), this->dir), static_cast<index_actor>(self)); ```suggestion co_yield std::move(slice); ``` There's no NRVO for coroutines. caf::error index_state::load_from_disk() { VAST_WARN("{} failed to remove partition file {} after recovery: {}", index, part_path, err); for (auto slice : *seg) + co_yield std::move(slice); } }(self, std::move(oversized_partitions), this->dir), static_cast<index_actor>(self));
codereview_new_cpp_data_5203
catalog(catalog_actor::stateful_pointer<catalog_state> self, return caf::make_error(ec::invalid_argument, "catalog expects queries " "not to have ids"); if (!has_expression) - return caf::make_error(ec::invalid_argument, "query had neither an " - "expression nor ids"); auto start = std::chrono::steady_clock::now(); auto result = self->state.lookup(query_context.expr); duration runtime = std::chrono::steady_clock::now() - start; You can replace this with an assertion now. catalog(catalog_actor::stateful_pointer<catalog_state> self, return caf::make_error(ec::invalid_argument, "catalog expects queries " "not to have ids"); if (!has_expression) + return caf::make_error(ec::invalid_argument, "catalog expects queries " + "to have an expression"); auto start = std::chrono::steady_clock::now(); auto result = self->state.lookup(query_context.expr); duration runtime = std::chrono::steady_clock::now() - start;
codereview_new_cpp_data_5256
static void proceed_handshake_picotls(h2o_socket_t *sock) sock->ssl->async.ptls_wbuf = (ptls_buffer_t){NULL}; } else #endif ptls_buffer_init(&wbuf, "", 0); int ret = ptls_handshake(sock->ssl->ptls, &wbuf, sock->ssl->input.encrypted->bytes, &consumed, NULL); h2o_buffer_consume(&sock->ssl->input.encrypted, consumed); nit: indent, clang-format might catch this static void proceed_handshake_picotls(h2o_socket_t *sock) sock->ssl->async.ptls_wbuf = (ptls_buffer_t){NULL}; } else #endif + { ptls_buffer_init(&wbuf, "", 0); + } int ret = ptls_handshake(sock->ssl->ptls, &wbuf, sock->ssl->input.encrypted->bytes, &consumed, NULL); h2o_buffer_consume(&sock->ssl->input.encrypted, consumed);
codereview_new_cpp_data_5257
static char *append_unsafe_string_apache(char *pos, const char *src, size_t len) if (len == 0) return pos; - const char *src_end = src + len; - for (; src != src_end; ++src) { if (' ' <= *src && *src < 0x7d && *src != '"') { *pos++ = *src; } else { ```suggestion for (const char *src_end = src + len; src != src_end; ++src) { ``` static char *append_unsafe_string_apache(char *pos, const char *src, size_t len) if (len == 0) return pos; + for (const char *src_end = src + len; src != src_end; ++src) { if (' ' <= *src && *src < 0x7d && *src != '"') { *pos++ = *src; } else {
codereview_new_cpp_data_5258
static void build_request(h2o_req_t *req, h2o_iovec_t *method, h2o_url_t *url, h h2o_iovec_vector_t cookie_values = {NULL}; int found_early_data = 0; if (H2O_LIKELY(req->headers.size != 0)) { - const h2o_header_t *h, *h_end; - for (h = req->headers.entries, h_end = h + req->headers.size; h != h_end; ++h) { if (h2o_iovec_is_token(h->name)) { const h2o_token_t *token = (void *)h->name; if (token->flags.proxy_should_drop_for_req) Can we do `for (const h2o_header_t *h = req->headers.entries, *h_end = h + req->headers.size; ...` here as well? static void build_request(h2o_req_t *req, h2o_iovec_t *method, h2o_url_t *url, h h2o_iovec_vector_t cookie_values = {NULL}; int found_early_data = 0; if (H2O_LIKELY(req->headers.size != 0)) { + for (const h2o_header_t *h = req->headers.entries, *h_end = h + req->headers.size; h != h_end; ++h) { if (h2o_iovec_is_token(h->name)) { const h2o_token_t *token = (void *)h->name; if (token->flags.proxy_should_drop_for_req)
codereview_new_cpp_data_5259
void h2o_dispose_request(h2o_req_t *req) h2o_timer_unlink(&req->_timeout_entry); if (req->pathconf != NULL && req->num_loggers != 0) { - h2o_logger_t **logger = req->loggers, **end = logger + req->num_loggers; - for (; logger != end; ++logger) { (*logger)->log_access((*logger), req); } } ```suggestion for (h2o_logger_t **logger = req->loggers, **end = logger + req->num_loggers; logger != end; ++logger) { ``` void h2o_dispose_request(h2o_req_t *req) h2o_timer_unlink(&req->_timeout_entry); if (req->pathconf != NULL && req->num_loggers != 0) { + for (h2o_logger_t **logger = req->loggers, **end = logger + req->num_loggers; logger != end; ++logger) { (*logger)->log_access((*logger), req); } }
codereview_new_cpp_data_5260
int h2o_dsr_parse_req(h2o_dsr_req_t *req, const char *_value, size_t _value_len, const char *name; size_t name_len; int64_t n; - struct st_h2o_dsr_req_quic_t quic_req; - memset(req, 0, sizeof(*req)); - memset(&quic_req, 0, sizeof(quic_req)); - req->transport.quic.address.sa.sa_family = AF_UNSPEC; while ((name = h2o_next_token(&iter, ',', ',', &name_len, &value)) != NULL) { if (h2o_memis(name, name_len, H2O_STRLIT("http"))) { ```c struct st_h2o_dsr_req_quic quic_req = {.address.sa.sa_family = AF_UNSPEC}; *req = (h2o_dsr_req_t){}; ``` Now that we have `quic_req`, I think the address of that structure should be set to `AF_UNSPEC`. And we can use compound assignment for the purpose. int h2o_dsr_parse_req(h2o_dsr_req_t *req, const char *_value, size_t _value_len, const char *name; size_t name_len; int64_t n; + struct st_h2o_dsr_req_quic_t quic_req = {.address.sa.sa_family = AF_UNSPEC}; + *req = (h2o_dsr_req_t){}; while ((name = h2o_next_token(&iter, ',', ',', &name_len, &value)) != NULL) { if (h2o_memis(name, name_len, H2O_STRLIT("http"))) {
codereview_new_cpp_data_5261
static void on_generator_dispose(void *_self) h2o_buffer_dispose(&self->last_content_before_send); } h2o_doublebuffer_dispose(&self->sending); - if (self->generator_disposed) *self->generator_disposed = 1; } ```suggestion if (self->generator_disposed != NULL) ``` Let's use boolean as the result of an if expression (https://github.com/h2o/h2o/wiki/Coding-Style#if). static void on_generator_dispose(void *_self) h2o_buffer_dispose(&self->last_content_before_send); } h2o_doublebuffer_dispose(&self->sending); + if (self->generator_disposed != NULL) *self->generator_disposed = 1; }
codereview_new_cpp_data_5262
static void on_write_complete(h2o_socket_t *sock, const char *err) /* reset the other buffer */ h2o_buffer_dispose(&conn->output.buf_in_flight); - /* as request write, unlink the deferred timeout that might have been set by `proceed_req` called above */ if (h2o_timer_is_linked(&conn->output.defer_timeout)) h2o_timer_unlink(&conn->output.defer_timeout); - #if !H2O_USE_LIBUV if (conn->state == H2O_HTTP2CLIENT_CONN_STATE_OPEN) { - if (conn->output.buf->size != 0 || !h2o_linklist_is_empty(&conn->output.sending_streams)) - h2o_socket_notify_write(sock, on_notify_write); return; } #endif - - /* write more, if possible */ do_emit_writereq(conn); close_connection_if_necessary(conn); } @deweerdt mentioned to me that there's a bare return in L1126 below. Could that be a problem if the `if` condition is false on L1124 i.e. could we return with the timer unlinked, while no new timer is linked? static void on_write_complete(h2o_socket_t *sock, const char *err) /* reset the other buffer */ h2o_buffer_dispose(&conn->output.buf_in_flight); + /* bail out if nothing can be written */ + if (conn->output.buf->size == 0 && h2o_linklist_is_empty(&conn->output.sending_streams)) { + assert(!h2o_timer_is_linked(&conn->output.defer_timeout)); + close_connection_if_necessary(conn); + return; + } + + /* run next write now instead of relying on the deferred timeout */ if (h2o_timer_is_linked(&conn->output.defer_timeout)) h2o_timer_unlink(&conn->output.defer_timeout); #if !H2O_USE_LIBUV if (conn->state == H2O_HTTP2CLIENT_CONN_STATE_OPEN) { + h2o_socket_notify_write(sock, on_notify_write); return; } #endif do_emit_writereq(conn); close_connection_if_necessary(conn); }
codereview_new_cpp_data_5478
int check_membership_Zr_star(const bn_t a){ return VALID; } -// Checks if input point s is in the subgroup G1. // The function assumes the input is known to be on the curve E1. int check_membership_G1(const ep_t p){ #if MEMBERSHIP_CHECK If I read that correctly (haven't worked with C for quite some time 😅 ), the function input is called `p` (?) ```suggestion // Checks if input point p is in the subgroup G1. ``` int check_membership_Zr_star(const bn_t a){ return VALID; } +// Checks if input point p is in the subgroup G1. // The function assumes the input is known to be on the curve E1. int check_membership_G1(const ep_t p){ #if MEMBERSHIP_CHECK
codereview_new_cpp_data_5707
void Player::createCard(const CardItem *sourceCard, case CardRelation::AttachTo: cmd.set_target_card_id(sourceCard->getId()); - cmd.set_target_mode(Command_CreateToken::REVERSE_ATTACH); break; case CardRelation::TransformInto: cmd.set_target_card_id(sourceCard->getId()); - cmd.set_target_mode(Command_CreateToken::TRANSFORM_FROM); break; } I don't like how these two enums are very closely related but have contrasting names, I'd say have them both be called reverse attach or attach to, otherwise if these were extended (#4016) we'd end up with 4 different names for 2 different things. void Player::createCard(const CardItem *sourceCard, case CardRelation::AttachTo: cmd.set_target_card_id(sourceCard->getId()); + cmd.set_target_mode(Command_CreateToken::ATTACH_TO); break; case CardRelation::TransformInto: cmd.set_target_card_id(sourceCard->getId()); + cmd.set_target_mode(Command_CreateToken::TRANSFORM_INTO); break; }
codereview_new_cpp_data_5708
bool DeckList::loadFromStream_Plain(QTextStream &in) } // find sideboard position, if marks are used this won't be needed - qsizetype sBStart = -1; if (inputs.indexOf(reSBMark, deckStart) == -1) { sBStart = inputs.indexOf(reSBComment, deckStart); if (sBStart == -1) { Qt 5.9.5 doesn't have the qsizetype typedef, the int was fine? bool DeckList::loadFromStream_Plain(QTextStream &in) } // find sideboard position, if marks are used this won't be needed + int sBStart = -1; if (inputs.indexOf(reSBMark, deckStart) == -1) { sBStart = inputs.indexOf(reSBComment, deckStart); if (sBStart == -1) {
codereview_new_cpp_data_5709
int OracleImporter::importCardsFromSet(const CardSetPtr &currentSet, power = getStringPropertyFromMap(card, "power"); toughness = getStringPropertyFromMap(card, "toughness"); - if (power.isEmpty() || power == "" || toughness.isEmpty() || toughness == ""){ ptSeparator = ""; } if (!(power.isEmpty() && toughness.isEmpty())) { .isEmpty() implicitly checks if it's "", so this can be simply reduced to `if (power.isEmpty() || toughenss.isEmpty())` I'd also consider doing this a different way possibly, as the next if statement handles a check to make sure they're both set properly. The if statement below seems to be wrong in its goals. A rough idea is to just build up a final response if power, then builderArray.append(power) if toughness, then builderArray.append(toughness) pt = builderArray.join("ptSeparator") as an example int OracleImporter::importCardsFromSet(const CardSetPtr &currentSet, power = getStringPropertyFromMap(card, "power"); toughness = getStringPropertyFromMap(card, "toughness"); + if (power.isEmpty() || toughness.isEmpty()){ ptSeparator = ""; } if (!(power.isEmpty() && toughness.isEmpty())) {
codereview_new_cpp_data_5710
void MessageLogWidget::logDrawCards(Player *player, int number) logMulligan(player, number); } else { if (deckSize == 0 && number == 0) { - appendHtmlServerMessage(tr("%1 had no cards left to draw.", "") .arg(sanitizeHtml(player->getName()))); } else { ```suggestion appendHtmlServerMessage(tr("%1 has no cards left to draw.") ``` most of our log messages use current tense instead of past tense, I think it'd make more sense to reword this in a way that works better in current tense, the original ticket has a suggestion in the way of "player draws from an empty library" or perhaps "player tries to draw from empty library", @tooomm might have some suggestions void MessageLogWidget::logDrawCards(Player *player, int number) logMulligan(player, number); } else { if (deckSize == 0 && number == 0) { + appendHtmlServerMessage(tr("%1 has no cards left to draw.") .arg(sanitizeHtml(player->getName()))); } else {
codereview_new_cpp_data_5711
void Player::createCard(const CardItem *sourceCard, const QString &dbCardName, b } else { cmd.set_annotation(""); } - if (conjured) { - cmd.set_destroy_on_zone_change(false); - } else { - cmd.set_destroy_on_zone_change(true); - } cmd.set_target_zone(sourceCard->getZone()->getName().toStdString()); cmd.set_x(gridPoint.x()); cmd.set_y(gridPoint.y()); You can simplify this if/else block ```suggestion cmd.set_destroy_on_zone_change(!conjured); ``` void Player::createCard(const CardItem *sourceCard, const QString &dbCardName, b } else { cmd.set_annotation(""); } + cmd.set_destroy_on_zone_change(!conjured); cmd.set_target_zone(sourceCard->getZone()->getName().toStdString()); cmd.set_x(gridPoint.x()); cmd.set_y(gridPoint.y());
codereview_new_cpp_data_5712
int OracleImporter::importCardsFromSet(const CardSetPtr &currentSet, } name = faceName; } - // support for array of cards this conjures - if (card.contains("spellbook")) { - auto spellbook = card.value("spellbook").toStringList(); - for (const auto &cName : spellbook) { - relatedCards.append(new CardRelation(cName, false, false, false, 1, true)); - } - } CardInfoPtr newCard = addCard(name + numComponent, text, isToken, properties, relatedCards, setInfo); numCards++; } I can't seem to find the "spellbook" property on any cards, does this attribute correlate to a feature that isn't available yet? int OracleImporter::importCardsFromSet(const CardSetPtr &currentSet, } name = faceName; } + + CardInfoPtr newCard = addCard(name + numComponent, text, isToken, properties, relatedCards, setInfo); numCards++; }
codereview_new_cpp_data_5717
void print(const char* fmt, ...) std::string get_cpu_arch() { -#define QUOTE(name) #name -#define STR(name) QUOTE(name) -#define ABI_NAME STR(REALM_ANDROID_ABI) - return ABI_NAME; -#undef STR -#undef QUOTE } } // namespace realm This looks a bit suspicious to me 🙂 But I [read a bit more about it](https://gcc.gnu.org/onlinedocs/cpp/Stringizing.html#Stringizing). However, this could be simplified (including passing in the `REALM_ANDROID_ABI`) by relying on the GCC preprocessor directives: ```suggestion #if defined(__arm__) return "armeabi-v7a"; #elif defined(__aarch64__) return "arm64-v8a"; #elif defined(__i386__) return "x86"; #elif defined(__x86_64__) return "x86_64"; #else return "unknown"; #endif ``` This has the benefit that we can control the values to match that of the other platforms. void print(const char* fmt, ...) std::string get_cpu_arch() { +#if defined(__arm__) + return "armeabi-v7a"; +#elif defined(__aarch64__) + return "arm64-v8a"; +#elif defined(__i386__) + return "x86"; +#elif defined(__x86_64__) + return "x86_64"; +#else + return "unknown"; +#endif } } // namespace realm
codereview_new_cpp_data_5721
void Clientlist::ProcessOPMailCommand(Client *c, std::string command_string, boo //Append saved channels to params auto const savedChannels = database.CurrentPlayerChannels(c->GetName()); if (savedChannels.length() > 0) { - parameters = parameters + ", " + savedChannels; } parameters = RemoveDuplicateChannels(parameters); } `parameters += fmt::format(“, {}”, savedChannels);` void Clientlist::ProcessOPMailCommand(Client *c, std::string command_string, boo //Append saved channels to params auto const savedChannels = database.CurrentPlayerChannels(c->GetName()); if (savedChannels.length() > 0) { + parameters += fmt::format(", {}", savedChannels); } parameters = RemoveDuplicateChannels(parameters); }
codereview_new_cpp_data_5722
void Clientlist::ProcessOPMailCommand(Client *c, std::string command_string, boo case CommandJoin: if (!command_directed) { //Append saved channels to params - auto const savedChannels = database.CurrentPlayerChannels(c->GetName()); - if (savedChannels.length() > 0) { - parameters += fmt::format(", {}", savedChannels); } parameters = RemoveDuplicateChannels(parameters); } `const auto`, would name it `saved_channels` as well. void Clientlist::ProcessOPMailCommand(Client *c, std::string command_string, boo case CommandJoin: if (!command_directed) { //Append saved channels to params + const auto saved_channels = database.CurrentPlayerChannels(c->GetName()); + if (saved_channels.length() > 0) { + parameters += fmt::format(", {}", saved_channels); } parameters = RemoveDuplicateChannels(parameters); }
codereview_new_cpp_data_5723
Doors::Doors(const DoorsRepository::Doors &door) : if (!door.dest_zone.empty() && Strings::ToLower(door.dest_zone) != "none" && !door.dest_zone.empty()) { m_has_destination_zone = true; } - if (!door.dest_zone.empty() && !door.zone.empty() && - Strings::ToLower(door.dest_zone) == Strings::ToLower(door.zone)) { m_same_destination_zone = true; } Want a newline here? Doors::Doors(const DoorsRepository::Doors &door) : if (!door.dest_zone.empty() && Strings::ToLower(door.dest_zone) != "none" && !door.dest_zone.empty()) { m_has_destination_zone = true; } + if (!door.dest_zone.empty() && !door.zone.empty() && Strings::EqualFold(door.dest_zone, door.zone)) { m_same_destination_zone = true; }
codereview_new_cpp_data_5724
void Object::HandleCombine(Client* user, const NewCombine_Struct* in_combine, Ob spec.recipe_id); auto results = content_db.QueryDatabase(query); - if(!results.Success() || results.RowCount() < 1 || results.RowCount() > 10) { auto outapp = new EQApplicationPacket(OP_TradeSkillCombine, 0); user->QueuePacket(outapp); safe_delete(outapp); Formatting. `if (` versus `if(` void Object::HandleCombine(Client* user, const NewCombine_Struct* in_combine, Ob spec.recipe_id); auto results = content_db.QueryDatabase(query); + if (!results.Success() || results.RowCount() < 1 || results.RowCount() > 10) { auto outapp = new EQApplicationPacket(OP_TradeSkillCombine, 0); user->QueuePacket(outapp); safe_delete(outapp);
codereview_new_cpp_data_5725
bool BotDatabase::SaveTimers(Bot* bot_inst) if (bot_timers[timer_index] <= Timer::GetCurrentTime()) continue; - query = StringFormat("REPLACE INTO `bot_timers` (`bot_id`, `timer_id`, `timer_value`) VALUES ('%u', '%u', '%u')", bot_inst->GetBotID(), (timer_index + 1), bot_timers[timer_index]); auto results = database.QueryDatabase(query); if (!results.Success()) { DeleteTimers(bot_inst->GetBotID()); While we’re in here, maybe make this use `fmt::format`? :) bool BotDatabase::SaveTimers(Bot* bot_inst) if (bot_timers[timer_index] <= Timer::GetCurrentTime()) continue; + query = fmt::format( + "REPLACE INTO `bot_timers` (`bot_id`, `timer_id`, `timer_value`) VALUES ('%u', '%u', '%u')", + bot_inst->GetBotID(), (timer_index + 1), bot_timers[timer_index] + ); auto results = database.QueryDatabase(query); if (!results.Success()) { DeleteTimers(bot_inst->GetBotID());
codereview_new_cpp_data_5726
bool BotDatabase::SaveTimers(Bot* bot_inst) continue; query = fmt::format( - "REPLACE INTO `bot_timers` (`bot_id`, `timer_id`, `timer_value`) VALUES ('%u', '%u', '%u')", bot_inst->GetBotID(), (timer_index + 1), bot_timers[timer_index] ); auto results = database.QueryDatabase(query); Can use `{}` for all three of these instead of `'%u'` since that's a `StringFormat` thing. bool BotDatabase::SaveTimers(Bot* bot_inst) continue; query = fmt::format( + "REPLACE INTO `bot_timers` (`bot_id`, `timer_id`, `timer_value`) VALUES ('{}', '{}', '{}')", bot_inst->GetBotID(), (timer_index + 1), bot_timers[timer_index] ); auto results = database.QueryDatabase(query);
codereview_new_cpp_data_5727
std::string BotDatabase::GetBotNameByID(const uint32 bot_id) bool BotDatabase::SaveBotCasterRange(const uint32 owner_id, const uint32 bot_id, const uint32 bot_caster_range_value) { - if (!owner_id || !bot_id) return false; - query = StringFormat( "UPDATE `bot_data`" - " SET `caster_range` = '%u'" - " WHERE `owner_id` = '%u'" - " AND `bot_id` = '%u'", bot_caster_range_value, owner_id, bot_id ); auto results = database.QueryDatabase(query); - if (!results.Success()) return false; return true; } Close this off please std::string BotDatabase::GetBotNameByID(const uint32 bot_id) bool BotDatabase::SaveBotCasterRange(const uint32 owner_id, const uint32 bot_id, const uint32 bot_caster_range_value) { + if (!owner_id || !bot_id) { return false; + } + query = fmt::format( "UPDATE `bot_data`" + " SET `caster_range` = '{}'" + " WHERE `owner_id` = '{}'" + " AND `bot_id` = '{}'", bot_caster_range_value, owner_id, bot_id ); auto results = database.QueryDatabase(query); + + if (!results.Success()) { return false; + } return true; }
codereview_new_cpp_data_5728
void EntityList::ClearFeignAggro(Mob *targ) if (it->second->IsNPC()) { if (parse->HasQuestSub(it->second->GetNPCTypeID(), EVENT_FEIGN_DEATH)) { - std::vector<std::any> args = { it->second }; - int i = parse->EventNPC(EVENT_FEIGN_DEATH, it->second->CastToNPC(), targ, "", 0); if (i != 0) { ++it; args isn't being passed here, it wasn't before either though for NPC void EntityList::ClearFeignAggro(Mob *targ) if (it->second->IsNPC()) { if (parse->HasQuestSub(it->second->GetNPCTypeID(), EVENT_FEIGN_DEATH)) { int i = parse->EventNPC(EVENT_FEIGN_DEATH, it->second->CastToNPC(), targ, "", 0); if (i != 0) { ++it;
codereview_new_cpp_data_5729
void Bot::PerformTradeWithClient(int16 begin_slot_id, int16 end_slot_id, Client* client->Message( Chat::Yellow, fmt::format( - "This bot already has {}, the trade has been cancelled!", item_link ).c_str() ); Maybe send bot name here? Like `X already has {}, the trade has been cancelled!`. void Bot::PerformTradeWithClient(int16 begin_slot_id, int16 end_slot_id, Client* client->Message( Chat::Yellow, fmt::format( + "{} already has {}, the trade has been cancelled!", + GetCleanName(), item_link ).c_str() );
codereview_new_cpp_data_5730
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 Missing a space here. 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_5731
void Client::SetEXP(uint64 set_exp, uint64 set_aaxp, bool isrezzexp) { } } - if (m_pp.exp != set_exp) { const auto exp_value = set_exp - m_pp.exp; const auto export_string = fmt::format("{}", exp_value); parse->EventPlayer(EVENT_EXP_GAIN, this, export_string, 0); } - if (m_pp.expAA != set_aaxp) { const auto aa_exp_value = set_aaxp - m_pp.expAA; const auto export_string = fmt::format("{}", aa_exp_value); parse->EventPlayer(EVENT_AA_EXP_GAIN, this, export_string, 0); These both should be gated with `parse->PlayerHasQuestSub(` void Client::SetEXP(uint64 set_exp, uint64 set_aaxp, bool isrezzexp) { } } + if (parse->PlayerHasQuestSub(EVENT_EXP_GAIN) && m_pp.exp != set_exp) { const auto exp_value = set_exp - m_pp.exp; const auto export_string = fmt::format("{}", exp_value); parse->EventPlayer(EVENT_EXP_GAIN, this, export_string, 0); } + if (parse->PlayerHasQuestSub(EVENT_AA_EXP_GAIN) && m_pp.expAA != set_aaxp) { const auto aa_exp_value = set_aaxp - m_pp.expAA; const auto export_string = fmt::format("{}", aa_exp_value); parse->EventPlayer(EVENT_AA_EXP_GAIN, this, export_string, 0);
codereview_new_cpp_data_5732
void PerlembParser::ExportEventVariables( } case EVENT_AA_EXP_GAIN: { - ExportVar(package_name.c_str(), "aa_exp_gained", data); - break; } case EVENT_EXP_GAIN: { - ExportVar(package_name.c_str(), "exp_gained", data); - break; } case EVENT_INSPECT: { Formatting is off here with the rest of the switch void PerlembParser::ExportEventVariables( } case EVENT_AA_EXP_GAIN: { + ExportVar(package_name.c_str(), "aa_exp_gained", data); + break; } case EVENT_EXP_GAIN: { + ExportVar(package_name.c_str(), "exp_gained", data); + break; } case EVENT_INSPECT: {
codereview_new_cpp_data_5733
int64 Mob::GetActSpellDamage(uint16 spell_id, int64 value, Mob* target) { chance += itembonuses.FrenziedDevastation + spellbonuses.FrenziedDevastation + aabonuses.FrenziedDevastation; //Crtical Hit Calculation pathway - if (chance > 0 || IsOfClientBot() && GetClass() == WIZARD && GetLevel() >= RuleI(Spells, WizCritLevel)) { int32 ratio = RuleI(Spells, BaseCritRatio); //Critical modifier is applied from spell effects only. Keep at 100 for live like criticals. Removed too many parentheses here. int64 Mob::GetActSpellDamage(uint16 spell_id, int64 value, Mob* target) { chance += itembonuses.FrenziedDevastation + spellbonuses.FrenziedDevastation + aabonuses.FrenziedDevastation; //Crtical Hit Calculation pathway + if (chance > 0 || (IsOfClientBot() && GetClass() == WIZARD && GetLevel() >= RuleI(Spells, WizCritLevel))) { int32 ratio = RuleI(Spells, BaseCritRatio); //Critical modifier is applied from spell effects only. Keep at 100 for live like criticals.
codereview_new_cpp_data_5734
ChatChannel *ChatChannelList::CreateChannel( { uint8 max_perm_player_channels = RuleI(Chat, MaxPermanentPlayerChannels); - if (!database.CheckChannelNameFilter(name) && !RuleB(Chat, ChannelsIgnoreNameFilter)) { if (!(owner == SYSTEM_OWNER)) { return nullptr; } Would put rule first so we’re not doing an unnecessary query here. ChatChannel *ChatChannelList::CreateChannel( { uint8 max_perm_player_channels = RuleI(Chat, MaxPermanentPlayerChannels); + if (!RuleB(Chat, ChannelsIgnoreNameFilter) && !database.CheckChannelNameFilter(name)) { if (!(owner == SYSTEM_OWNER)) { return nullptr; }
codereview_new_cpp_data_5735
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_5736
void ChatChannelList::AddToFilteredNames(const std::string& name) { return; } - // Check if name is already in the FilteredNames vector - bool is_found = Strings::Contains(ChatChannelList::GetFilteredNames(), name); - // Add name to the filtered names vector if it is not already present - if (!is_found) { auto filtered_names = GetFilteredNames(); // Get current filter name list filtered_names.push_back(name); // Add new name to local filtered names list SetFilteredNameList(filtered_names); // Set filtered names list to match local filtered names list Can use this inside the condition itself. void ChatChannelList::AddToFilteredNames(const std::string& name) { return; } // Add name to the filtered names vector if it is not already present + if (!Strings::Contains(ChatChannelList::GetFilteredNames(), name)) { auto filtered_names = GetFilteredNames(); // Get current filter name list filtered_names.push_back(name); // Add new name to local filtered names list SetFilteredNameList(filtered_names); // Set filtered names list to match local filtered names list
codereview_new_cpp_data_5737
int main(int argc, char** argv) { safe_delete(task_manager); safe_delete(npc_scale_manager); command_deinit(); - if (RuleB(Bots, AllowBots)) { bot_command_deinit(); } safe_delete(parse); Nit: `AllowBots` seems strange, how about `Bots:Enabled` int main(int argc, char** argv) { safe_delete(task_manager); safe_delete(npc_scale_manager); command_deinit(); + if (RuleB(Bots, Enabled)) { bot_command_deinit(); } safe_delete(parse);
codereview_new_cpp_data_5738
void NPC::AIYellForHelp(Mob *sender, Mob *attacker) LogAIYellForHelp( "NPC [{}] ID [{}] is starting to scan", - (!this ? "NULL MOB" : GetCleanName()), - (!this ? 0 : GetID()) ); for (auto &close_mob : entity_list.GetCloseMobList(sender)) { This change shouldn't be necessary. `this` can never be null in well formed code, so something else has to be the cause of the crash if it's crashing here (or maybe the line numbers were wrong?) (checking `this` against null I guess was a thing back in the 90s, but that's because the compilers/implementations were special ...) void NPC::AIYellForHelp(Mob *sender, Mob *attacker) LogAIYellForHelp( "NPC [{}] ID [{}] is starting to scan", + GetCleanName(), + GetID() ); for (auto &close_mob : entity_list.GetCloseMobList(sender)) {
codereview_new_cpp_data_5739
Mob* Mob::GetPet() { } bool Mob::HasPet() const { - if (GetPetID() == 0) { return false; } Extra new line here. Mob* Mob::GetPet() { } bool Mob::HasPet() const { if (GetPetID() == 0) { return false; }
codereview_new_cpp_data_5740
void LuaMod::GetExperienceForKill(Client *self, Mob *against, uint64 &returnValu } } -void LuaMod::CalcSpellEffectValue_formula(Mob *self, int64 formula, int64 base_value, int64 max_value, int caster_level, uint16 spell_id, int ticsremaining, int64 &returnValue, bool &ignoreDefault) { int start = lua_gettop(L); int64 retval = 0; Why is formula `int64` here? void LuaMod::GetExperienceForKill(Client *self, Mob *against, uint64 &returnValu } } +void LuaMod::CalcSpellEffectValue_formula(Mob *self, uint32 formula, int64 base_value, int64 max_value, int caster_level, uint16 spell_id, int ticsremaining, int64 &returnValue, bool &ignoreDefault) { int start = lua_gettop(L); int64 retval = 0;
codereview_new_cpp_data_5741
uint64 LuaParser::GetExperienceForKill(Client *self, Mob *against, bool &ignoreD return retval; } -int64 LuaParser::CalcSpellEffectValue_formula(Mob *self, int64 formula, int64 base_value, int64 max_value, int caster_level, uint16 spell_id, int ticsremaining, bool &ignoreDefault) { int64 retval = 0; for (auto &mod : mods_) { Why is formula `int64` here? uint64 LuaParser::GetExperienceForKill(Client *self, Mob *against, bool &ignoreD return retval; } +int64 LuaParser::CalcSpellEffectValue_formula(Mob *self, uint32 formula, int64 base_value, int64 max_value, int caster_level, uint16 spell_id, int ticsremaining, bool &ignoreDefault) { int64 retval = 0; for (auto &mod : mods_) {
codereview_new_cpp_data_5742
int64 Mob::CalcSpellEffectValue(uint16 spell_id, int effect_id, int caster_level } // generic formula calculations -int64 Mob::CalcSpellEffectValue_formula(int64 formula, int64 base_value, int64 max_value, int caster_level, uint16 spell_id, int ticsremaining) { #ifdef LUA_EQEMU int64 lua_ret = 0; Why is formula `int64` here? int64 Mob::CalcSpellEffectValue(uint16 spell_id, int effect_id, int caster_level } // generic formula calculations +int64 Mob::CalcSpellEffectValue_formula(uint32 formula, int64 base_value, int64 max_value, int caster_level, uint16 spell_id, int ticsremaining) { #ifdef LUA_EQEMU int64 lua_ret = 0;
codereview_new_cpp_data_5743
void Client::CompleteConnect() // enforce some rules.. if (!CanEnterZone()) { LogInfo("Kicking character [{}] from zone, not allowed here (missing requirements)", GetCleanName()); - GoToSafeCoords(RuleI(World, FailedRequirementBootZoneID), 0); return; } } It's possible that the client still can't even enter what's configured for a default here. It might make sense to have it reroute them to bind void Client::CompleteConnect() // enforce some rules.. if (!CanEnterZone()) { LogInfo("Kicking character [{}] from zone, not allowed here (missing requirements)", GetCleanName()); + GoToBind(); return; } }
codereview_new_cpp_data_5744
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 Wouldn't you want this value to be at least `1` instead of `0` uint32 ZoneDatabase::GetDoorsCountPlusOne() int ZoneDatabase::GetDoorsDBCountPlusOne(std::string zone_short_name, int16 version) { const auto query = fmt::format( + "SELECT COALESCE(MAX(doorid), 1) FROM doors " "WHERE zone = '{}' AND (version = {} OR version = -1)", zone_short_name, version
codereview_new_cpp_data_5745
std::string EQ::InventoryProfile::GetCustomItemData(int16 slot_id, std::string i return ""; } -int EQ::InventoryProfile::GetItemStatValue(uint32 item_id, std::string identifier) { if (identifier.empty()) { return 0; } Could be const. std::string EQ::InventoryProfile::GetCustomItemData(int16 slot_id, std::string i return ""; } +const int EQ::InventoryProfile::GetItemStatValue(uint32 item_id, std::string identifier) { if (identifier.empty()) { return 0; }
codereview_new_cpp_data_5746
luabind::scope lua_register_client() { .def("SetEXP", (void(Lua_Client::*)(uint64,uint64))&Lua_Client::SetEXP) .def("SetEXP", (void(Lua_Client::*)(uint64,uint64,bool))&Lua_Client::SetEXP) .def("SetEXPEnabled", (void(Lua_Client::*)(bool))&Lua_Client::SetEXPEnabled) - .def("SetEXPModifier", (void(Lua_Client::*)(uint32,double))&Lua_Client::SetEXPModifier) .def("SetEXPModifier", (void(Lua_Client::*)(uint32,double,int16))&Lua_Client::SetEXPModifier) .def("SetEbonCrystals", (void(Lua_Client::*)(uint32))&Lua_Client::SetEbonCrystals) Extra new line here. luabind::scope lua_register_client() { .def("SetEXP", (void(Lua_Client::*)(uint64,uint64))&Lua_Client::SetEXP) .def("SetEXP", (void(Lua_Client::*)(uint64,uint64,bool))&Lua_Client::SetEXP) .def("SetEXPEnabled", (void(Lua_Client::*)(bool))&Lua_Client::SetEXPEnabled) .def("SetEXPModifier", (void(Lua_Client::*)(uint32,double))&Lua_Client::SetEXPModifier) .def("SetEXPModifier", (void(Lua_Client::*)(uint32,double,int16))&Lua_Client::SetEXPModifier) .def("SetEbonCrystals", (void(Lua_Client::*)(uint32))&Lua_Client::SetEbonCrystals)
codereview_new_cpp_data_5747
void Client::CalculateExp(uint32 in_add_exp, uint32 &add_exp, uint32 &add_aaxp, add_exp -= add_aaxp; //Enforce Percent XP Cap per kill, if rule is enabled - int KillPercentXPCap = RuleI(Character, KillExperiencePercentCap); - if (KillPercentXPCap >= 0) { // If the cap is == -1, do nothing - unsigned long int ExperienceForLevel = (unsigned long int)(GetEXPForLevel(GetLevel() + 1) - GetEXPForLevel(GetLevel())); // Amt of xp needed to complete current level - unsigned short exp_percent = ceil((float)((float)add_exp / ExperienceForLevel) * 100); // Percent of current level earned - if (exp_percent > KillPercentXPCap) { // Determine if the earned XP percent is higher than the percent cap - add_exp = floor(ExperienceForLevel * (KillPercentXPCap / 100.0)); // Set the added xp to the set cap. } } Snake case: `kill_percent_xp_cap` void Client::CalculateExp(uint32 in_add_exp, uint32 &add_exp, uint32 &add_aaxp, add_exp -= add_aaxp; //Enforce Percent XP Cap per kill, if rule is enabled + int kill_percent_xp_cap = RuleI(Character, KillExperiencePercentCap); + if (kill_percent_xp_cap >= 0) { // If the cap is == -1, do nothing + uint32 experience_for_level = (uint32 )(GetEXPForLevel(GetLevel() + 1) - GetEXPForLevel(GetLevel())); // Amt of xp needed to complete current level + uint8 exp_percent = ceil((float)((float)add_exp / experience_for_level) * 100); // Percent of current level earned + if (exp_percent > kill_percent_xp_cap) { // Determine if the earned XP percent is higher than the percent cap + add_exp = floor(experience_for_level * (kill_percent_xp_cap / 100.0)); // Set the added xp to the set cap. } }
codereview_new_cpp_data_5748
void Client::CalculateExp(uint32 in_add_exp, uint32 &add_exp, uint32 &add_aaxp, add_exp -= add_aaxp; //Enforce Percent XP Cap per kill, if rule is enabled - int KillPercentXPCap = RuleI(Character, KillExperiencePercentCap); - if (KillPercentXPCap >= 0) { // If the cap is == -1, do nothing - unsigned long int ExperienceForLevel = (unsigned long int)(GetEXPForLevel(GetLevel() + 1) - GetEXPForLevel(GetLevel())); // Amt of xp needed to complete current level - unsigned short exp_percent = ceil((float)((float)add_exp / ExperienceForLevel) * 100); // Percent of current level earned - if (exp_percent > KillPercentXPCap) { // Determine if the earned XP percent is higher than the percent cap - add_exp = floor(ExperienceForLevel * (KillPercentXPCap / 100.0)); // Set the added xp to the set cap. } } Snake case: `experience_for_level` void Client::CalculateExp(uint32 in_add_exp, uint32 &add_exp, uint32 &add_aaxp, add_exp -= add_aaxp; //Enforce Percent XP Cap per kill, if rule is enabled + int kill_percent_xp_cap = RuleI(Character, KillExperiencePercentCap); + if (kill_percent_xp_cap >= 0) { // If the cap is == -1, do nothing + uint32 experience_for_level = (uint32 )(GetEXPForLevel(GetLevel() + 1) - GetEXPForLevel(GetLevel())); // Amt of xp needed to complete current level + uint8 exp_percent = ceil((float)((float)add_exp / experience_for_level) * 100); // Percent of current level earned + if (exp_percent > kill_percent_xp_cap) { // Determine if the earned XP percent is higher than the percent cap + add_exp = floor(experience_for_level * (kill_percent_xp_cap / 100.0)); // Set the added xp to the set cap. } }
codereview_new_cpp_data_5749
void Client::MaxSkills() for (const auto &s : EQ::skills::GetSkillTypeMap()) { auto current_skill_value = ( EQ::skills::IsSpecializedSkill(s.first) ? - 50 : content_db.GetSkillCap(GetClass(), s.first, GetLevel()) ); Is 50 hard-coded or defined somewhere? void Client::MaxSkills() for (const auto &s : EQ::skills::GetSkillTypeMap()) { auto current_skill_value = ( EQ::skills::IsSpecializedSkill(s.first) ? + MAX_SPECIALIZED_SKILL : content_db.GetSkillCap(GetClass(), s.first, GetLevel()) );
codereview_new_cpp_data_5750
void command_suspendmulti(Client *c, const Seperator *sep) const std::string reason = sep->arg[3] ? sep->argplus[3] : ""; auto l = AccountRepository::GetWhere( - content_db, fmt::format( "LOWER(charname) IN ({})", Strings::Implode(", ", v) Accounts should be handled by `database` I think, not the content db void command_suspendmulti(Client *c, const Seperator *sep) const std::string reason = sep->arg[3] ? sep->argplus[3] : ""; auto l = AccountRepository::GetWhere( + database, fmt::format( "LOWER(charname) IN ({})", Strings::Implode(", ", v)
codereview_new_cpp_data_5751
void command_suspendmulti(Client *c, const Seperator *sep) a.suspendeduntil = std::time(nullptr) + (days * 86400); a.suspend_reason = reason; - if (!AccountRepository::UpdateOne(content_db, a)) { c->Message( Chat::White, fmt::format( This one should be `database` too void command_suspendmulti(Client *c, const Seperator *sep) a.suspendeduntil = std::time(nullptr) + (days * 86400); a.suspend_reason = reason; + if (!AccountRepository::UpdateOne(database, a)) { c->Message( Chat::White, fmt::format(
codereview_new_cpp_data_5752
void QuestManager::depop_withtimer(int npc_type) { void QuestManager::depopall(int npc_type) { QuestManagerCurrentQuestVars(); - if ((owner && owner->IsNPC() && (npc_type > 0)) || npc_type > 0) { entity_list.DepopAll(npc_type); } else { LogQuests("QuestManager::depopall called with nullptr owner, non-NPC owner, or invalid NPC Type ID. Probably syntax error in quest file."); Can probably just remove the owner checks and QuestManagerCurrentQuestVars() altogether since they’re not used and don’t matter. void QuestManager::depop_withtimer(int npc_type) { void QuestManager::depopall(int npc_type) { QuestManagerCurrentQuestVars(); + if (npc_type > 0) { entity_list.DepopAll(npc_type); } else { LogQuests("QuestManager::depopall called with nullptr owner, non-NPC owner, or invalid NPC Type ID. Probably syntax error in quest file.");
codereview_new_cpp_data_5753
bool BotDatabase::LoadItemSlots(const uint32 bot_id, std::map<uint16, uint32>& m fmt::format( "bot_id = {}", bot_id - ).c_str() ); if (l.empty() || !l[0].inventories_index) { return false; Not sure this needs to be `c_str()` as repositories take in native std strings bool BotDatabase::LoadItemSlots(const uint32 bot_id, std::map<uint16, uint32>& m fmt::format( "bot_id = {}", bot_id + ) ); if (l.empty() || !l[0].inventories_index) { return false;
codereview_new_cpp_data_5754
bool BotDatabase::LoadItemSlots(const uint32 bot_id, std::map<uint16, uint32>& m fmt::format( "bot_id = {}", bot_id - ).c_str() ); if (l.empty() || !l[0].inventories_index) { return false; `l.empty()` should be suffice bool BotDatabase::LoadItemSlots(const uint32 bot_id, std::map<uint16, uint32>& m fmt::format( "bot_id = {}", bot_id + ) ); if (l.empty() || !l[0].inventories_index) { return false;
codereview_new_cpp_data_5755
std::map<uint16, uint32> Bot::GetBotItemSlots() GetCleanName() ).c_str() ); - return m; } return m; This return seems redundant because the fallback will end up returning the same thing std::map<uint16, uint32> Bot::GetBotItemSlots() GetCleanName() ).c_str() ); } return m;
codereview_new_cpp_data_5756
int command_init(void) command_add("nukeitem", "[Item ID] - Removes the specified Item ID from you or your player target's inventory", AccountStatus::GMLeadAdmin, command_nukeitem) || command_add("object", "List|Add|Edit|Move|Rotate|Copy|Save|Undo|Delete - Manipulate static and tradeskill objects within the zone", AccountStatus::GMAdmin, command_object) || command_add("oocmute", "[0|1] - Enable or Disable Server OOC", AccountStatus::GMMgmt, command_oocmute) || - command_add("opcode", "- Reloads all server patches", AccountStatus::GMImpossible, command_opcode) || command_add("path", "view and edit pathing", AccountStatus::GMMgmt, command_path) || command_add("peekinv", "[equip/gen/cursor/poss/limbo/curlim/trib/bank/shbank/allbank/trade/world/all] - Print out contents of your player target's inventory", AccountStatus::GMAdmin, command_peekinv) || command_add("peqzone", "[Zone ID|Zone Short Name] - Teleports you to the specified zone if you meet the requirements.", AccountStatus::Player, command_peqzone) || Probably can remove the dash at the beginning. Almost no current descriptions start with a dash int command_init(void) command_add("nukeitem", "[Item ID] - Removes the specified Item ID from you or your player target's inventory", AccountStatus::GMLeadAdmin, command_nukeitem) || command_add("object", "List|Add|Edit|Move|Rotate|Copy|Save|Undo|Delete - Manipulate static and tradeskill objects within the zone", AccountStatus::GMAdmin, command_object) || command_add("oocmute", "[0|1] - Enable or Disable Server OOC", AccountStatus::GMMgmt, command_oocmute) || + command_add("opcode", "Reloads all server patches", AccountStatus::GMImpossible, command_opcode) || command_add("path", "view and edit pathing", AccountStatus::GMMgmt, command_path) || command_add("peekinv", "[equip/gen/cursor/poss/limbo/curlim/trib/bank/shbank/allbank/trade/world/all] - Print out contents of your player target's inventory", AccountStatus::GMAdmin, command_peekinv) || command_add("peqzone", "[Zone ID|Zone Short Name] - Teleports you to the specified zone if you meet the requirements.", AccountStatus::Player, command_peqzone) ||
codereview_new_cpp_data_5757
Bot* EntityList::GetRandomBot(const glm::vec3& location, float distance, Bot* ex return nullptr; } - return bots_in_range[zone->random.Int(0, bots_in_range .size() - 1)]; } #endif Formatting with `bots_in_range` and `.size` Bot* EntityList::GetRandomBot(const glm::vec3& location, float distance, Bot* ex return nullptr; } + return bots_in_range[zone->random.Int(0, bots_in_range.size() - 1)]; } #endif
codereview_new_cpp_data_5758
NPC::NPC(const NPCType *npc_type_data, Spawn2 *in_respawn, const glm::vec4 &posi AISpellVar.idle_beneficial_chance = static_cast<uint8> (RuleI(Spells, AI_IdleBeneficialChance)); // It's possible for IsBot() to not be set yet during Bot loading, so have to use an alternative to catch Bots - if (!EQ::ValueWithin(npc_type_data->npc_spells_id, 3001, 3016)) { AI_Init(); AI_Start(); #ifdef BOTS Constants? BotSpellIDs::Warrior for example. NPC::NPC(const NPCType *npc_type_data, Spawn2 *in_respawn, const glm::vec4 &posi AISpellVar.idle_beneficial_chance = static_cast<uint8> (RuleI(Spells, AI_IdleBeneficialChance)); // It's possible for IsBot() to not be set yet during Bot loading, so have to use an alternative to catch Bots + if (!EQ::ValueWithin(npc_type_data->npc_spells_id, EQ::constants::BotSpellIDs::Warrior, EQ::constants::BotSpellIDs::Berserker)) { AI_Init(); AI_Start(); #ifdef BOTS
codereview_new_cpp_data_5759
bool EntityList::LimitCheckName(const char *npc_name) while (it != npc_list.end()) { NPC *npc = it->second; if (npc) { - if (strcasecmp(npc_name, npc->GetName()) == 0) { return false; } } We do want their name before `EntityList::MakeNameUnique()` has touched it, which `GetName()` does not get us bool EntityList::LimitCheckName(const char *npc_name) while (it != npc_list.end()) { NPC *npc = it->second; if (npc) { + if (strcasecmp(npc_name, npc->GetRawNPCTypeName()) == 0) { return false; } }
codereview_new_cpp_data_5760
void Client::AddEXP(uint32 in_add_exp, uint8 conlevel, bool resexp) { // Check for Unused AA Cap. If at or above cap, set AAs to cap, set aaexp to 0 and set aa percentage to 0. // Doing this here means potentially one kill wasted worth of experience, but easiest to put it here than to rewrite this function. - if (aaexp > 0) { - int aa_cap = RuleI(AA, UnusedAAPointCap); if (m_pp.aapoints == aa_cap) { MessageString(Chat::Red, AA_CAP); aaexp = 0; m_epp.perAA = 0; } else if (m_pp.aapoints > aa_cap) { - MessageString(Chat::Red, OVER_AA_CAP); m_pp.aapoints = aa_cap; aaexp = 0; m_epp.perAA = 0; If both trees set these 2 variables to 0, can have the setters outside of either condition specifically. Just do >= then inside send message based on > or == and set AA to cap if >. void Client::AddEXP(uint32 in_add_exp, uint8 conlevel, bool resexp) { // Check for Unused AA Cap. If at or above cap, set AAs to cap, set aaexp to 0 and set aa percentage to 0. // Doing this here means potentially one kill wasted worth of experience, but easiest to put it here than to rewrite this function. + int aa_cap = RuleI(AA, UnusedAAPointCap); + + if (aa_cap > 0 && aaexp > 0) { + char val1[20] = {0}; + char val2[20] = {0}; + if (m_pp.aapoints == aa_cap) { MessageString(Chat::Red, AA_CAP); aaexp = 0; m_epp.perAA = 0; } else if (m_pp.aapoints > aa_cap) { + MessageString(Chat::Red, OVER_AA_CAP, ConvertArray(aa_cap, val1), ConvertArray(aa_cap, val2)); m_pp.aapoints = aa_cap; aaexp = 0; m_epp.perAA = 0;
codereview_new_cpp_data_5761
void Client::AddEXP(uint32 in_add_exp, uint8 conlevel, bool resexp) { int aa_cap = RuleI(AA, UnusedAAPointCap); if (aa_cap > 0 && aaexp > 0) { - char val1[20] = {0}; - char val2[20] = {0}; - if (m_pp.aapoints == aa_cap) { MessageString(Chat::Red, AA_CAP); aaexp = 0; m_epp.perAA = 0; } else if (m_pp.aapoints > aa_cap) { - MessageString(Chat::Red, OVER_AA_CAP, ConvertArray(aa_cap, val1), ConvertArray(aa_cap, val2)); m_pp.aapoints = aa_cap; aaexp = 0; m_epp.perAA = 0; `MessageString(Chat::Red, OVER_AA_CAP, fmt::format_int(aa_cap).c_str(), fmt::format_int(aa_cap).c_str());` Would probably be better so you don't need the stack buffers void Client::AddEXP(uint32 in_add_exp, uint8 conlevel, bool resexp) { int aa_cap = RuleI(AA, UnusedAAPointCap); if (aa_cap > 0 && aaexp > 0) { if (m_pp.aapoints == aa_cap) { MessageString(Chat::Red, AA_CAP); aaexp = 0; m_epp.perAA = 0; } else if (m_pp.aapoints > aa_cap) { + MessageString(Chat::Red, OVER_AA_CAP, fmt::format_int(aa_cap).c_str(), fmt::format_int(aa_cap).c_str()); m_pp.aapoints = aa_cap; aaexp = 0; m_epp.perAA = 0;
codereview_new_cpp_data_5762
void command_faction_association(Client *c, const Seperator *sep) // default to self unless target is also a client auto target = c; - if (c->GetTarget() && c->GetTarget()->IsClient()) target = c->GetTarget()->CastToClient(); target->RewardFaction(atoi(sep->arg[1]), atoi(sep->arg[2])); } Would really prefer if we just close these. There's a few other places of implied brackets void command_faction_association(Client *c, const Seperator *sep) // default to self unless target is also a client auto target = c; + if (c->GetTarget() && c->GetTarget()->IsClient()) { target = c->GetTarget()->CastToClient(); + } target->RewardFaction(atoi(sep->arg[1]), atoi(sep->arg[2])); }
codereview_new_cpp_data_5764
void WorldDatabase::GetCharSelectInfo(uint32 account_id, EQApplicationPacket **o if (x == 0 && y == 0 && z == 0 && heading == 0) { auto zone = GetZone(pp.binds[4].zone_id); if (zone) { - pp.binds[4].x = zone->safe_x; - pp.binds[4].y = zone->safe_y; - pp.binds[4].z = zone->safe_z; - pp.binds[4].heading = zone->safe_heading; } } } There's a logic change here I think might be unintended. The previous code only set `binds[4]` to the safe coordinates if x,y,z,h were all 0, otherwise it set it to the x,y,z,h values. The new code only ever sets it to the safe coordinates void WorldDatabase::GetCharSelectInfo(uint32 account_id, EQApplicationPacket **o if (x == 0 && y == 0 && z == 0 && heading == 0) { auto zone = GetZone(pp.binds[4].zone_id); if (zone) { + x = zone->safe_x; + y = zone->safe_y; + z = zone->safe_z; + heading = zone->safe_heading; } } }
codereview_new_cpp_data_5765
void WorldDatabase::GetCharSelectInfo(uint32 account_id, EQApplicationPacket **o heading = zone->safe_heading; } } } } pp.binds[0] = pp.binds[4]; These need to be added back I think void WorldDatabase::GetCharSelectInfo(uint32 account_id, EQApplicationPacket **o heading = zone->safe_heading; } } + pp.binds[4].x = x; + pp.binds[4].y = y; + pp.binds[4].z = z; + pp.binds[4].heading = heading; } } pp.binds[0] = pp.binds[4];
codereview_new_cpp_data_5766
bool TaskManager::LoadTasks(int single_task) activity_data->goal_match_list = task_activity.goal_match_list; activity_data->goal_count = task_activity.goalcount; activity_data->deliver_to_npc = task_activity.delivertonpc; - activity_data->zone_version = task_activity.zone_version ? task_activity.zone_version : -1; // zones activity_data->zones = task_activity.zones; This will break restricting to zone version 0 bool TaskManager::LoadTasks(int single_task) activity_data->goal_match_list = task_activity.goal_match_list; activity_data->goal_count = task_activity.goalcount; activity_data->deliver_to_npc = task_activity.delivertonpc; + activity_data->zone_version = task_activity.zone_version && task_activity.zone_version >= 0 ? task_activity.zone_version : -1; // zones activity_data->zones = task_activity.zones;
codereview_new_cpp_data_5767
void command_lootsim(Client *c, const Seperator *sep) { int arguments = sep->argnum; - if (arguments < 3) { c->Message(Chat::White, "Usage: #lootsim [npc_type_id] [loottable_id] [iterations] [loot_log_enabled=0]"); return; } Since we're not validating below, we can just stop them from getting there with invalid inputs. Or add validation. ```cpp if (arguments < 3 || !sep->IsNumber(1) || !sep->IsNumber(2) || !sep->IsNumber(3)) { ``` void command_lootsim(Client *c, const Seperator *sep) { int arguments = sep->argnum; + if (arguments < 3 || !sep->IsNumber(1) || !sep->IsNumber(2) || !sep->IsNumber(3)) { c->Message(Chat::White, "Usage: #lootsim [npc_type_id] [loottable_id] [iterations] [loot_log_enabled=0]"); return; }
codereview_new_cpp_data_5768
bool SharedTaskManager::HandleCompletedActivities(SharedTask* s) std::array<bool, MAXACTIVITIESPERTASK> completed_steps; completed_steps.fill(true); auto activity_states = s->GetActivityState(); std::sort(activity_states.begin(), activity_states.end(), [](const auto& lhs, const auto& rhs) { return lhs.step < rhs.step; }); Comments: What is this doing and why bool SharedTaskManager::HandleCompletedActivities(SharedTask* s) std::array<bool, MAXACTIVITIESPERTASK> completed_steps; completed_steps.fill(true); + // multiple activity ids may share a step, sort so previous step completions can be checked auto activity_states = s->GetActivityState(); std::sort(activity_states.begin(), activity_states.end(), [](const auto& lhs, const auto& rhs) { return lhs.step < rhs.step; });
codereview_new_cpp_data_5769
void NPC::AddLootDrop( // unsure if required to equip, YOLO for now - if (item2->ItemType == EQ::item::ItemTypeBow) SetBowEquipped(true); - if (item2->ItemType == EQ::item::ItemTypeArrow) SetArrowEquipped(true); if (loot_drop.equip_item > 0) { uint8 eslot = 0xFF; Brackets here maybe? void NPC::AddLootDrop( // unsure if required to equip, YOLO for now + if (item2->ItemType == EQ::item::ItemTypeBow) { SetBowEquipped(true); + } + if (item2->ItemType == EQ::item::ItemTypeArrow) { SetArrowEquipped(true); + } if (loot_drop.equip_item > 0) { uint8 eslot = 0xFF;
codereview_new_cpp_data_5770
bool Client::Death(Mob* killerMob, int64 damage, uint16 spell, EQ::skills::Skill } if (exploss > 0 && RuleB(Character, DeathKeepLevel)) { - int32 totalExp = GetEXP(); - uint32 levelMinExp = GetEXPForLevel(killed_level); - int32 levelExp = totalExp - levelMinExp; - if (exploss > levelExp) { - exploss = levelExp; } } `snake_case` eg `total_exp` for locally scoped variables Same for below variables bool Client::Death(Mob* killerMob, int64 damage, uint16 spell, EQ::skills::Skill } if (exploss > 0 && RuleB(Character, DeathKeepLevel)) { + int32 total_exp = GetEXP(); + uint32 level_min_exp = GetEXPForLevel(killed_level); + int32 level_exp = total_exp - level_min_exp; + if (exploss > level_exp) { + exploss = level_exp; } }
codereview_new_cpp_data_5771
void perl_register_quest() package.add("clear_zone_flag", &Perl__clear_zone_flag); package.add("clearspawntimers", &Perl__clearspawntimers); package.add("collectitems", &Perl__collectitems); - package.add("Commify", &Perl__commify); package.add("completedtasksinset", &Perl__completedtasksinset); package.add("countitem", &Perl__countitem); package.add("countspawnednpcs", &Perl__countspawnednpcs); This is case sensitive so need to undo this change to prevent api breakage void perl_register_quest() package.add("clear_zone_flag", &Perl__clear_zone_flag); package.add("clearspawntimers", &Perl__clearspawntimers); package.add("collectitems", &Perl__collectitems); + package.add("commify", &Perl__commify); package.add("completedtasksinset", &Perl__completedtasksinset); package.add("countitem", &Perl__countitem); package.add("countspawnednpcs", &Perl__countspawnednpcs);
codereview_new_cpp_data_5772
void Client::Handle_OP_PickPocket(const EQApplicationPacket *app) return; } else { - Message(0, "Your attempt at stealing was unsuccessful."); } QueuePacket(outapp); Could be a Client String: 12898 Your attempt at stealing was unsuccessful. void Client::Handle_OP_PickPocket(const EQApplicationPacket *app) return; } else { + MessageString(Chat::White, STEAL_UNSUCCESSFUL); } QueuePacket(outapp);
codereview_new_cpp_data_5773
void Client::Trader_EndTrader() { } safe_delete(outapp); } - safe_delete(gis); } database.DeleteTraderItem(CharacterID()); Just undo this change and push a new commit to this pr's branch to resolve the #2266 duplicate void Client::Trader_EndTrader() { } safe_delete(outapp); + safe_delete(gis); } } database.DeleteTraderItem(CharacterID());
codereview_new_cpp_data_5774
void Client::Handle_OP_LootItem(const EQApplicationPacket *app) return; } - auto* l = (LootItem_Struct*) app->pBuffer; - auto entity = entity_list.GetID(l->entity_id); if (!entity) { auto outapp = new EQApplicationPacket(OP_LootComplete, 0); QueuePacket(outapp); Can just use the current `LootingItem_Struct` for this (and cast the `lootee` field for the entity list api) void Client::Handle_OP_LootItem(const EQApplicationPacket *app) return; } + auto* l = (LootingItem_Struct*) app->pBuffer; + auto entity = entity_list.GetID(static_cast<uint16>(l->lootee)); if (!entity) { auto outapp = new EQApplicationPacket(OP_LootComplete, 0); QueuePacket(outapp);
codereview_new_cpp_data_5775
void Object::HandleAutoCombine(Client* user, const RecipeAutoCombine_Struct* rac } // Character does not have the required skill. - if(spec.skill_needed > 0 && user->GetSkill(spec.tradeskill) < spec.skill_needed ) { // Notify client. user->Message(Chat::Red, "You are not skilled enough."); user->QueuePacket(outapp); `if (` versus `if(` void Object::HandleAutoCombine(Client* user, const RecipeAutoCombine_Struct* rac } // Character does not have the required skill. + if (spec.skill_needed > 0 && user->GetSkill(spec.tradeskill) < spec.skill_needed) { // Notify client. user->Message(Chat::Red, "You are not skilled enough."); user->QueuePacket(outapp);
codereview_new_cpp_data_5776
bool Mob::SpellEffect(Mob* caster, uint16 spell_id, float partial, int level_ove if (IsClient()) { if (caster->IsClient()) { - if (!entity_list.IsInSameGroupOrRaidGroup(caster->CastToClient(), this->CastToClient())) { caster->Message(Chat::Red, "Your target must be a group member for this spell."); break; } `this` is implied. bool Mob::SpellEffect(Mob* caster, uint16 spell_id, float partial, int level_ove if (IsClient()) { if (caster->IsClient()) { + if (!entity_list.IsInSameGroupOrRaidGroup(caster->CastToClient(), CastToClient())) { caster->Message(Chat::Red, "Your target must be a group member for this spell."); break; }
codereview_new_cpp_data_5777
void Mob::FixZ(int32 z_find_offset /*= 5*/, bool fix_client_z /*= false*/) { return; } - if (IsBoat()) { return; } Since this is running through a significant hot path, I'd like this to reference a mob scoped private member variable boolean that is loaded on spawn and we don't have to run OR's in this check repeatedly Otherwise I'm good with the overall premise and change of this PR void Mob::FixZ(int32 z_find_offset /*= 5*/, bool fix_client_z /*= false*/) { return; } + if (GetIsBoat()) { return; }
codereview_new_cpp_data_5855
bool strtolower(std::string &str, std::string::size_type offs) bool IsValidChar(WChar key, CharSetFilter afilter) { switch (afilter) { - case CS_ALPHANUMERAL: return IsPrintable(key); - case CS_NUMERAL: return (key >= '0' && key <= '9'); - case CS_NUMERAL_SPACE: return (key >= '0' && key <= '9') || key == ' '; - case CS_NUMERAL_SIGNED: return (key >= '0' && key <= '9') || key == '-'; - case CS_ALPHA: return IsPrintable(key) && !(key >= '0' && key <= '9'); - case CS_HEXADECIMAL: return (key >= '0' && key <= '9') || (key >= 'a' && key <= 'f') || (key >= 'A' && key <= 'F'); - default: NOT_REACHED(); } } Indentation seems to have gotten wrong here. (Maybe check your editor settings.) bool strtolower(std::string &str, std::string::size_type offs) bool IsValidChar(WChar key, CharSetFilter afilter) { switch (afilter) { + case CS_ALPHANUMERAL: return IsPrintable(key); + case CS_NUMERAL: return (key >= '0' && key <= '9'); + case CS_NUMERAL_SPACE: return (key >= '0' && key <= '9') || key == ' '; + case CS_NUMERAL_SIGNED: return (key >= '0' && key <= '9') || key == '-'; + case CS_ALPHA: return IsPrintable(key) && !(key >= '0' && key <= '9'); + case CS_HEXADECIMAL: return (key >= '0' && key <= '9') || (key >= 'a' && key <= 'f') || (key >= 'A' && key <= 'F'); + default: NOT_REACHED(); } }
codereview_new_cpp_data_5947
void ThroughputSubscriber::DataReaderListener::on_data_available( } } last_seq_num = seq_num; } if ((last_seq_num_ + size) < last_seq_num) { lost_samples_ += last_seq_num - last_seq_num_ - size; } last_seq_num_ = last_seq_num; - received_samples_ += 1; // release the reader loan if (ReturnCode_t::RETCODE_OK != reader->return_loan(data_seq, infos)) ```suggestion received_samples_ += size; ``` void ThroughputSubscriber::DataReaderListener::on_data_available( } } last_seq_num = seq_num; + received_samples_ += 1; } if ((last_seq_num_ + size) < last_seq_num) { lost_samples_ += last_seq_num - last_seq_num_ - size; } last_seq_num_ = last_seq_num; // release the reader loan if (ReturnCode_t::RETCODE_OK != reader->return_loan(data_seq, infos))
codereview_new_cpp_data_5948
DataWriterImpl::DataWriterImpl( , qos_(&qos == &DATAWRITER_QOS_DEFAULT ? publisher_->get_default_datawriter_qos() : qos) , listener_(listen) , history_(get_topic_attributes(qos_, *topic_, type_), type_->m_typeSize, qos_.endpoint().history_memory_policy, - [&]( const InstanceHandle_t& handle) -> void { if (nullptr != listener_) ```suggestion [this]( ``` DataWriterImpl::DataWriterImpl( , qos_(&qos == &DATAWRITER_QOS_DEFAULT ? publisher_->get_default_datawriter_qos() : qos) , listener_(listen) , history_(get_topic_attributes(qos_, *topic_, type_), type_->m_typeSize, qos_.endpoint().history_memory_policy, + [this]( const InstanceHandle_t& handle) -> void { if (nullptr != listener_)
codereview_new_cpp_data_5949
bool StatefulWriter::has_been_fully_delivered( std::lock_guard<RecursiveTimedMutex> guard(mp_mutex); bool found = false; // Sequence number has not been generated by this WriterHistory. - if (seq_num > (mp_history->next_sequence_number() - 1)) { return false; } ```suggestion if (seq_num >= mp_history->next_sequence_number()) ``` bool StatefulWriter::has_been_fully_delivered( std::lock_guard<RecursiveTimedMutex> guard(mp_mutex); bool found = false; // Sequence number has not been generated by this WriterHistory. + if (seq_num >= mp_history->next_sequence_number()) { return false; }
codereview_new_cpp_data_5950
bool StatelessWriter::change_removed_by_history( bool StatelessWriter::has_been_fully_delivered( const SequenceNumber_t& seq_num) const { if (getMatchedReadersSize() > 0) { return is_acked_by_all(seq_num); Should we also check here that the sequence has been generated? Perhaps we should add a new test .... ```suggestion // Sequence number has not been generated by this WriterHistory. if (seq_num >= mp_history->next_sequence_number()) { return false; } if (getMatchedReadersSize() > 0) ``` bool StatelessWriter::change_removed_by_history( bool StatelessWriter::has_been_fully_delivered( const SequenceNumber_t& seq_num) const { + // Sequence number has not been generated by this WriterHistory + { + std::lock_guard<RecursiveTimedMutex> guard(mp_mutex); + if (seq_num >= mp_history->next_sequence_number()) + { + return false; + } + } + if (getMatchedReadersSize() > 0) { return is_acked_by_all(seq_num);
codereview_new_cpp_data_5951
bool ReaderProxy::has_been_delivered( const SequenceNumber_t& seq_number, bool& found) const { - for (auto change : changes_for_reader_) { - if (change.getSequenceNumber() == seq_number) - { - found = true; - return change.has_been_delivered(); - } } return false; } No need to traverse the collection: ```suggestion if (seq_num <= changes_low_mark_) { // This means the change has been acknowledged, so it should have been delivered return true; } ChangeIterator it = find_change(seq_num, true); if (it != changes_for_reader_.end()) { found = true; return change.has_been_delivered(); } return false; ``` bool ReaderProxy::has_been_delivered( const SequenceNumber_t& seq_number, bool& found) const { + if (seq_number <= changes_low_mark_) { + // Change has already been acknowledged, so it has been delivered + return true; + } + + ChangeIterator it = find_change(seq_number, true); + if (it != changes_for_reader_.end()) + { + found = true; + return change.has_been_delivered(); } + return false; }
codereview_new_cpp_data_5952
bool StatefulWriter::has_been_fully_delivered( bool ret_code = reader->has_been_delivered(seq_num, found); if (found && !ret_code) { - // The change has not been fully delivered if at least is found in one ReaderProxy without having been - // delivered. return false; } } ```suggestion // The change has not been fully delivered if it is pending delivery on at least one ReaderProxy. ``` bool StatefulWriter::has_been_fully_delivered( bool ret_code = reader->has_been_delivered(seq_num, found); if (found && !ret_code) { + // The change has not been fully delivered if it is pending delivery on at least one ReaderProxy. return false; } }
codereview_new_cpp_data_5953
DataWriterImpl::DataWriterImpl( , qos_(&qos == &DATAWRITER_QOS_DEFAULT ? publisher_->get_default_datawriter_qos() : qos) , listener_(listen) , history_(get_topic_attributes(qos_, *topic_, type_), type_->m_typeSize, qos_.endpoint().history_memory_policy, - [&]( const InstanceHandle_t& handle) -> void { if (nullptr != listener_) ```suggestion [this]( ``` DataWriterImpl::DataWriterImpl( , qos_(&qos == &DATAWRITER_QOS_DEFAULT ? publisher_->get_default_datawriter_qos() : qos) , listener_(listen) , history_(get_topic_attributes(qos_, *topic_, type_), type_->m_typeSize, qos_.endpoint().history_memory_policy, + [this]( const InstanceHandle_t& handle) -> void { if (nullptr != listener_)
codereview_new_cpp_data_5954
#include <fastdds/dds/log/Log.hpp> #include <fastdds/rtps/common/Time_t.h> #include <fastdds/rtps/writer/RTPSWriter.h> -#include <fastdds/rtps/writer/StatefulWriter.h> namespace eprosima { namespace fastdds { I think we don't need this anymore. ```suggestion ``` #include <fastdds/dds/log/Log.hpp> #include <fastdds/rtps/common/Time_t.h> #include <fastdds/rtps/writer/RTPSWriter.h> namespace eprosima { namespace fastdds {
codereview_new_cpp_data_5955
bool StatelessWriter::change_removed_by_history( } const uint64_t sequence_number = change->sequenceNumber.to64long(); - if (sequence_number < last_sequence_number_sent_) { unsent_changes_cond_.notify_all(); } Should this be `<=` ? We should notify the condition whenever `wait_for_acknowledgement` should be unblocked bool StatelessWriter::change_removed_by_history( } const uint64_t sequence_number = change->sequenceNumber.to64long(); + if (sequence_number <= last_sequence_number_sent_) { unsent_changes_cond_.notify_all(); }
codereview_new_cpp_data_5958
bool DataReaderHistory::get_first_untaken_info( { std::lock_guard<RecursiveTimedMutex> lock(*getMutex()); - for (auto &it : data_available_instances_) { auto& instance_changes = it.second->cache_changes; if (!instance_changes.empty()) Minor Uncrustify ```suggestion for (auto& it : data_available_instances_) ``` bool DataReaderHistory::get_first_untaken_info( { std::lock_guard<RecursiveTimedMutex> lock(*getMutex()); + for (auto& it : data_available_instances_) { auto& instance_changes = it.second->cache_changes; if (!instance_changes.empty())
codereview_new_cpp_data_5960
TEST_F(UDPv6Tests, send_to_wrong_interface) Locators locators_begin(locator_list.begin()); Locators locators_end(locator_list.end()); - IPLocator::setIPv6(outputChannelLocator, std::string("fe80::ffff:6f6f:6f6f")); std::vector<octet> message = { 'H', 'e', 'l', 'l', 'o' }; ASSERT_FALSE(send_resource_list.at(0)->send(message.data(), (uint32_t)message.size(), &locators_begin, &locators_end, ```suggestion std::vector<octet> message = { 'H', 'e', 'l', 'l', 'o' }; ``` TEST_F(UDPv6Tests, send_to_wrong_interface) Locators locators_begin(locator_list.begin()); Locators locators_end(locator_list.end()); std::vector<octet> message = { 'H', 'e', 'l', 'l', 'o' }; ASSERT_FALSE(send_resource_list.at(0)->send(message.data(), (uint32_t)message.size(), &locators_begin, &locators_end,
codereview_new_cpp_data_5961
TEST_F(StatisticsDomainParticipantTests, DeleteParticipantAfterDeleteContainedEn STATISTICS_DATAWRITER_QOS)); // 3. Perform a delete_contained_entities() in the statistics participant - EXPECT_EQ(statistics_participant->delete_contained_entities(), ReturnCode_t::RETCODE_OK); // 4. Delete the participant EXPECT_EQ(eprosima::fastdds::dds::DomainParticipantFactory::get_instance()-> I would call this method from `participant` and not from `statistics_participant`, as this would be the most expected way to do it from a user. (It should be the same, but just in case, to avoid virtualization method problems). TEST_F(StatisticsDomainParticipantTests, DeleteParticipantAfterDeleteContainedEn STATISTICS_DATAWRITER_QOS)); // 3. Perform a delete_contained_entities() in the statistics participant + EXPECT_EQ(participant->delete_contained_entities(), ReturnCode_t::RETCODE_OK); // 4. Delete the participant EXPECT_EQ(eprosima::fastdds::dds::DomainParticipantFactory::get_instance()->