Skip to content

Assemble the Event Engine

The Course
•
30 min study

The engine is three files, and the split is itself a design decision. engine.h is the public interface: event types, results, the Rule base, the move-only Engine and the constrained count_events template. engine.cpp holds everything a consumer should not depend on: the visitors, the validation helpers and the parser. main.cpp is a thin text adapter that groups lines into batches and prints a report. Tests and compile contracts include only the header, so anything they can see is something you have promised.

Reading engine.h

  • Plain event structs and a closed variant. No constructors and no invariants, because an event is a request that may be refused (Day 1).
  • BatchResult { Error error; std::optional<std::size_t> index; }. A scoped enum for the kind of failure, an optional for the event that caused it (Day 4).
  • ParseResult = std::variant<Event, ParseError>. The parser returns a value or a reason, never a half-built event (Day 5).
  • class Rule with a virtual destructor and one pure const function. The comment above accepts states the semantic contract the compiler cannot check: no retained references, no external effects (Day 2).
  • class Engine deletes its copy operations and defaults its moves. apply borrows a std::span<const Event>. snapshot returns an owning Inventory by value.
  • count_events is defined in the header, because templates must be visible where they are instantiated, and is constrained with std::predicate<Predicate, const Event&> (Day 3).

Reading engine.cpp

ApplyVisitor holds Inventory& state and has one overload per event. Each overload checks its values first, then the inventory facts: a Create checks for a duplicate before checking the item limit, so adding an existing item to a full inventory reports duplicate, the more specific error. Each overload writes to state only after all its checks pass.

Engine::apply is the transaction. In order: reject an oversized batch with no index; copy state_ into staged; for each index, visit the event against staged, then ask every rule about staged; return {error, index} at the first failure; after the loop, state_.swap(staged). Exactly one line writes live state, and it is the last.

The parser splits on | into views, stops after four fields, converts numbers strictly, and copies names into std::string before returning. ExportVisitor and export_inventory produce the canonical text.

Reading main.cpp

main installs TotalLimit(1500), then reads lines with std::getline. It strips one trailing \r. A blank line calls flush, which counts a malformed batch as rejected, applies a non-empty batch and counts its result, and ignores an empty clean one. After a malformed line, or once a batch would exceed 256 events, it skips lines until the next separator. After the loop it checks std::cin.bad() for a real read error, flushes once more for a final batch with no trailing blank line, and prints the report. It returns nonzero if writing the report failed.

Two limits of the adapter are documented rather than hidden. The 256-event cap bounds the stored batch, but getline can still allocate for one very long line. Adding a rule affects only future batches; it does not revalidate what was already committed.

Predict and run

Predict before running C++
#include <iostream>
#include <initializer_list>

int main() {
    int accepted = 0, rejected = 0;
    bool first_valid = true, second_valid = false, third_valid = true;
    for (bool valid : {first_valid,second_valid,third_valid}) {
        if (valid) { ++accepted; } else { ++rejected; }
    }
    std::cout << accepted << " " << rejected << "\n";
    return 0;
}
Check your prediction
Text
2 1

The report counts batches, not events, because the batch is the unit of the transaction. The rejected sample batch contained a valid create|1|5|Nuts, yet it adds nothing to an accepted count: it was never committed. Counting events would report one success for a change that does not exist.

Run the event engine

Typed event engine C++
#include "engine.h" #include <iostream> static bool flush(Engine& engine, std::vector<Event>& pending, bool malformed, std::size_t& accepted, std::size_t& rejected) { if (malformed) { ++rejected; } else if (!pending.empty()) { const auto result = engine.apply(pending); if (result.error == Error::none) { ++accepted; } else { ++rejected; } } pending.clear(); return false; } int main() { Engine engine; engine.add_rule(std::make_unique<TotalLimit>(1500)); std::vector<Event> pending; std::size_t accepted = 0, rejected = 0; bool malformed = false; std::string line; while (std::getline(std::cin, line)) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } if (line.empty()) { malformed = flush(engine, pending, malformed, accepted, rejected); continue; } if (malformed) { continue; } // Consume until the next batch separator. ParseResult parsed = parse_event(line); if (std::holds_alternative<ParseError>(parsed) || pending.size() >= 256) { malformed = true; continue; } pending.push_back(std::get<Event>(std::move(parsed))); } if (std::cin.bad()) { std::cerr << "Input error\n"; return 1; } flush(engine, pending, malformed, accepted, rejected); std::cout << export_inventory(engine.snapshot()); std::cout << "Total: " << total_quantity(engine.snapshot()) << "\nAccepted batches: " << accepted << "\nRejected batches: " << rejected << '\n'; return std::cout ? 0 : 1; } #include "engine.h" #include <sstream> #include <utility> static bool valid_name(const std::string& name) { if (name.empty() || name.size() > 40 || name.front() == ' ' || name.back() == ' ') { return false; } for (unsigned char ch : name) { if (ch < 32 || ch > 126 || ch == '|') { return false; } } return true; } static bool valid_id(int id) { return id >= 1 && id <= 9999; } struct ApplyVisitor { Inventory& state; Error operator()(const Create& event) const { if (!valid_id(event.id) || !valid_name(event.name) || event.quantity < 0 || event.quantity > 1000) { return Error::invalid; } if (state.find(event.id) != state.end()) { return Error::duplicate; } if (state.size() >= 100) { return Error::full; } state.emplace(event.id, Item{event.name, event.quantity}); return Error::none; } Error operator()(const Adjust& event) const { if (!valid_id(event.id) || event.delta < -1000 || event.delta > 1000) { return Error::invalid; } auto found = state.find(event.id); if (found == state.end()) { return Error::missing; } const int next = found->second.quantity + event.delta; // [-1000,2000], no int overflow. if (next < 0 || next > 1000) { return Error::invalid; } found->second.quantity = next; return Error::none; } Error operator()(const Rename& event) const { if (!valid_id(event.id) || !valid_name(event.name)) { return Error::invalid; } auto found = state.find(event.id); if (found == state.end()) { return Error::missing; } found->second.name = event.name; return Error::none; } }; long total_quantity(const Inventory& inventory) { long total = 0; for (const auto& entry : inventory) { total += entry.second.quantity; } return total; } bool TotalLimit::accepts(const Inventory& proposed, const Event& event) const { (void)event; return total_quantity(proposed) <= maximum_; } bool Engine::add_rule(std::unique_ptr<Rule> rule) { if (!rule) { return false; } rules_.push_back(std::move(rule)); return true; } BatchResult Engine::apply(std::span<const Event> events) { if (events.size() > 256) { return {Error::batch_too_large, std::nullopt}; } Inventory staged = state_; for (std::size_t index = 0; index < events.size(); ++index) { Error error = std::visit(ApplyVisitor{staged}, events[index]); if (error != Error::none) { return {error, index}; } for (const auto& rule : rules_) { if (!rule->accepts(staged, events[index])) { return {Error::rule_rejected, index}; } } } state_.swap(staged); return {Error::none, std::nullopt}; } static std::optional<int> number(std::string_view text, bool signed_value) { if (text.empty()) { return std::nullopt; } std::size_t start = signed_value && text.front() == '-' ? 1 : 0; if (start == text.size()) { return std::nullopt; } for (std::size_t i = start; i < text.size(); ++i) { if (text[i] < '0' || text[i] > '9') { return std::nullopt; } } std::istringstream input{std::string(text)}; int value = 0; if (!(input >> value)) { return std::nullopt; } return value; } ParseResult parse_event(std::string_view line) { std::vector<std::string_view> fields; std::size_t start = 0; for (;;) { const auto end = line.find('|', start); fields.push_back(line.substr(start, end == std::string_view::npos ? end : end - start)); if (end == std::string_view::npos) { break; } start = end + 1; if (fields.size() >= 4) { return ParseError{"Too many fields"}; } } if (fields.size() < 3) { return ParseError{"Missing fields"}; } auto id = number(fields[1], false); if (!id || !valid_id(*id)) { return ParseError{"Invalid id"}; } if (fields[0] == "create" && fields.size() == 4) { auto quantity = number(fields[2], false); std::string name(fields[3]); if (!quantity || *quantity > 1000 || !valid_name(name)) { return ParseError{"Invalid create"}; } return Event{Create{*id, std::move(name), *quantity}}; } if (fields[0] == "adjust" && fields.size() == 3) { auto delta = number(fields[2], true); if (!delta || *delta < -1000 || *delta > 1000) { return ParseError{"Invalid adjustment"}; } return Event{Adjust{*id, *delta}}; } if (fields[0] == "rename" && fields.size() == 3) { std::string name(fields[2]); if (!valid_name(name)) { return ParseError{"Invalid name"}; } return Event{Rename{*id, std::move(name)}}; } return ParseError{"Unknown event or field count"}; } struct ExportVisitor { std::string operator()(const Create& e) const { return "create|" + std::to_string(e.id) + "|" + std::to_string(e.quantity) + "|" + e.name; } std::string operator()(const Adjust& e) const { return "adjust|" + std::to_string(e.id) + "|" + std::to_string(e.delta); } std::string operator()(const Rename& e) const { return "rename|" + std::to_string(e.id) + "|" + e.name; } }; std::string export_event(const Event& event) { return std::visit(ExportVisitor{}, event); } std::string export_inventory(const Inventory& inventory) { std::ostringstream output; for (const auto& entry : inventory) { output << entry.first << '|' << entry.second.quantity << '|' << entry.second.name << '\n'; } return output.str(); } #ifndef EVENT_ENGINE_H #define EVENT_ENGINE_H #include <concepts> #include <cstddef> #include <functional> #include <map> #include <memory> #include <optional> #include <span> #include <string> #include <string_view> #include <variant> #include <vector> struct Create { int id; std::string name; int quantity; }; struct Adjust { int id; int delta; }; struct Rename { int id; std::string name; }; using Event = std::variant<Create, Adjust, Rename>; struct Item { std::string name; int quantity; }; using Inventory = std::map<int, Item>; enum class Error { none, invalid, duplicate, missing, full, rule_rejected, batch_too_large }; struct BatchResult { Error error; std::optional<std::size_t> index; }; struct ParseError { std::string message; }; using ParseResult = std::variant<Event, ParseError>; ParseResult parse_event(std::string_view line); // Borrows input during call; returns owned strings. std::string export_event(const Event& event); // Canonical text for a valid event, no newline. std::string export_inventory(const Inventory& inventory); // ID order, newline per item. long total_quantity(const Inventory& inventory); class Rule { public: virtual ~Rule() = default; // Called on staged state AFTER each event. Must not retain references or produce // external effects; only engine state participates in the transaction. virtual bool accepts(const Inventory& proposed, const Event& event) const = 0; }; class TotalLimit final : public Rule { public: explicit TotalLimit(long maximum) : maximum_(maximum) { } // Require maximum >= 0. bool accepts(const Inventory& proposed, const Event& event) const override; private: long maximum_; }; class Engine { public: Engine() = default; Engine(const Engine&) = delete; Engine& operator=(const Engine&) = delete; Engine(Engine&&) = default; Engine& operator=(Engine&&) = default; bool add_rule(std::unique_ptr<Rule> rule); // Non-NULL owned rule; future batches only. BatchResult apply(std::span<const Event> events); Inventory snapshot() const { return state_; } // Owning copy, independent of later updates. private: Inventory state_; std::vector<std::unique_ptr<Rule>> rules_; }; // Definition stays in header for instantiation. Predicates inspect, never retain, // their argument; exceptions/external effects are outside the engine contract. template<class Predicate> requires std::predicate<Predicate, const Event&> std::size_t count_events(std::span<const Event> events, Predicate matches) { std::size_t count = 0; for (const Event& event : events) { if (std::invoke(matches, event)) { ++count; } } return count; } #endif create|2|10|Bolts adjust|2|-3 create|1|5|Nuts adjust|2|-99 create|1|5|Nuts rename|2|Steel bolts
Check your prediction
Text
1|5|Nuts
2|7|Steel bolts
Total: 12
Accepted batches: 2
Rejected batches: 1

Now edit the input and predict each result before running:

  • Clear the input. The report shows Total: 0 and zero batches of each kind: an empty input is a success that changes nothing.
  • A valid create followed by malformed with no blank line between them. The whole batch is rejected, and the create never appears.
  • Add a blank line and a new valid batch after it. The adapter recovers, and the new batch is accepted.
  • create|1|1000|One, then create|2|501|Two in the same batch. The total would be 1501, so TotalLimit rejects the batch at index 1, and neither item exists.
  • create|1|10|One with Windows line endings. CRLF is stripped, and the result is the same as with LF.

Each of these is one of the adapter cases in scripts/cpp-advanced-checks.py.

Practice

Exercise

Your turn

Model the adapter's counting. Each input batch is described by a std::optional<bool>: std::nullopt for a run of blank lines with no events, true for an applied batch and false for a rejected one. Write std::pair<std::size_t, std::size_t> count_batches(const std::vector<std::optional<bool>>& outcomes) that ignores the empty entries. Check two inputs and print:

Shell
sample: accepted 2, rejected 1
blank lines only: accepted 0, rejected 0

The sample is {true, std::nullopt, false, true} and the second input is {std::nullopt, std::nullopt}.

Your workspace C++
#include <iostream>
#include <optional>
#include <utility>
#include <vector>

int main() {
    // Write count_batches and print both results.
    return 0;
}
Hint 1: the idea

Count at the same granularity as the transaction boundary, and only for batches that were actually attempted.

Hint 2: a first step

Inside the loop, if (!outcome) { continue; }, then increment exactly one of the two counters based on *outcome.

Show one solution
Run the solution C++
#include <iostream>
#include <optional>
#include <utility>
#include <vector>

std::pair<std::size_t, std::size_t> count_batches(const std::vector<std::optional<bool>>& outcomes) {
    std::size_t accepted = 0, rejected = 0;
    for (const auto& outcome : outcomes) {
        if (!outcome) { continue; }
        if (*outcome) { ++accepted; } else { ++rejected; }
    }
    return {accepted, rejected};
}

int main() {
    const auto [a1, r1] = count_batches({true, std::nullopt, false, true});
    std::cout << "sample: accepted " << a1 << ", rejected " << r1 << "\n";
    const auto [a2, r2] = count_batches({std::nullopt, std::nullopt});
    std::cout << "blank lines only: accepted " << a2 << ", rejected " << r2 << "\n";
    return 0;
}
Text
sample: accepted 2, rejected 1
blank lines only: accepted 0, rejected 0

std::optional<bool> has three states, and the code must not confuse "empty" with "false": if (!outcome) tests emptiness, while *outcome reads the stored value. Writing if (outcome == false) instead would compare the value only when one is present, which also works, but reads as if it tested emptiness. The project's flush makes the same three-way decision. Next you read the tests that prove the engine's guarantees.

Was this article helpful?

Your response is saved on this device.