Skip to content

The Typed Event Engine Brief

The Course
•
25 min study

Today you assemble everything from the week into one program: a typed event engine for an inventory. Before reading any of its code, read the specification. Every rule below exists for a reason you have already met, and most of them are tested somewhere in the project. A brief that states limits as exact numbers is one you can check; "names should be reasonable" is not.

The data

  • Events. Create{id, name, quantity}, Adjust{id, delta} and Rename{id, name}, joined in std::variant<Create, Adjust, Rename> (Day 1).
  • Item IDs are 1..9999. Quantities are 0..1000. Deltas are -1000..1000.
  • Names have 1..40 printable ASCII characters, with no | and no leading or trailing space. That keeps the text format unambiguous (Day 5).
  • At most 100 items and at most 256 events per batch. Every input the engine stores is bounded, so no input can make it grow without limit.

The ranges are also chosen so arithmetic is safe: a quantity of at most 1000 plus a delta in -1000..1000 stays within -1000..2000, far from int overflow, and the total of 100 items fits easily in a long.

The behavior

  • Rules inspect proposed state after each event (Day 4). The application installs TotalLimit(1500), owned through std::unique_ptr<Rule> (Day 2).
  • Batches are atomic. If any event or rule rejects a batch, all of its changes are discarded, and live state is exactly what it was.
  • Results are explicit. A failure returns an Error and the zero-based index of the failing event. An oversized batch is a preflight failure with no index. An empty library batch succeeds and changes nothing.
  • Snapshots are owning copies, so a caller cannot observe later batches through an old snapshot.

The text adapter

  • Input lines are create|id|quantity|name, adjust|id|delta and rename|id|name, separated into batches by blank lines.
  • A malformed line rejects its entire input batch; the adapter skips to the next blank line.
  • Blank lines alone do not count as batches. End of input flushes the final batch. CRLF line endings are accepted.
  • The report prints the inventory in ID order as id|quantity|name, then Total:, Accepted batches: and Rejected batches:.

What it does not promise

The brief is just as specific about what is out of scope. There is no recovery from allocation failure, no rollback of effects outside the inventory, no thread safety and no deduplication of replayed events: repeating an Adjust applies it again. Stating these keeps users from relying on guarantees nobody tested.

Predict and run

Predict before running C++
#include <iostream>

int main() {
    long quantity = 7 + 5;
    std::cout << "Total: " << quantity << "\n";
    return 0;
}
Check your prediction
Text
Total: 12

That is the final total of the sample input, and you can derive it from the brief before running anything. The sample has three batches:

  1. create|2|10|Bolts, adjust|2|-3: accepted, so item 2 has 7.
  2. create|1|5|Nuts, adjust|2|-99: the adjustment would take item 2 to -92, so the batch is rejected at index 1, and the staged Nuts record is discarded with it.
  3. create|1|5|Nuts, rename|2|Steel bolts: accepted. Item 1 can be created now, because the failed batch never created it.

So the report shows 1|5|Nuts, 2|7|Steel bolts, Total: 12, two accepted batches and one rejected. If the second batch's Nuts had leaked into live state, the third batch would fail as a duplicate and the counts would differ. A sample input with a failure in the middle is a test of atomicity, not just a demo.

Practice

Exercise

Your turn

Write bool valid_name(const std::string& name) exactly as the brief defines names, and check it on the boundary cases below. Print each name in brackets with ok or rejected:

Shell
[Bolts] ok
[] rejected
[ Bolts] rejected
[Bolts ] rejected
[Nuts|Bolts] rejected
[xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx] ok
[xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx] rejected
[Steel bolts] ok

The two long names have 40 and 41 characters.

Your workspace C++
#include <iostream>
#include <string>
#include <vector>

int main() {
    const std::vector<std::string> names{"Bolts", "", " Bolts", "Bolts ", "Nuts|Bolts",
        std::string(40, 'x'), std::string(41, 'x'), "Steel bolts"};
    // Write valid_name and print each result.
    return 0;
}
Hint 1: the idea

Check the cheap whole-string conditions first: empty, too long, a space at either end. Then check each character.

Hint 2: a first step

Loop with for (unsigned char ch : name) and reject ch < 32 || ch > 126 || ch == '|'. Converting to unsigned char keeps bytes above 127 from becoming negative numbers.

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

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;
}

int main() {
    const std::vector<std::string> names{"Bolts", "", " Bolts", "Bolts ", "Nuts|Bolts",
        std::string(40, 'x'), std::string(41, 'x'), "Steel bolts"};
    for (const std::string& name : names) {
        std::cout << "[" << name << "] " << (valid_name(name) ? "ok" : "rejected") << "\n";
    }
    return 0;
}
Text
[Bolts] ok
[] rejected
[ Bolts] rejected
[Bolts ] rejected
[Nuts|Bolts] rejected
[xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx] ok
[xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx] rejected
[Steel bolts] ok

The empty() test must come first: front() and back() on an empty string are undefined behavior, and || stops evaluating at the first true operand. The pair of 40 and 41 characters is the boundary test that catches >= written for >. This is the same function as valid_name in the project's engine.cpp, used by both the parser and the apply visitor. Next you assemble the engine and run it.

Was this article helpful?

Your response is saved on this device.