Skip to content

Parse Borrowed Text into Owned Events

The Course
•
35 min study

The input adapter reads one line at a time into a single std::string with std::getline, and overwrites that string for the next line. The parser turns each line into an Event that goes into a pending batch and may live for hundreds more lines. That sets up a clear lifetime split. Inside the parser, borrowing is ideal: splitting a line into fields with std::string_view costs no allocation. Leaving the parser, everything must be owned, because the line the views point into is about to be overwritten.

So parse_event takes a std::string_view, slices it into field views, validates them, and copies the name into a std::string member of the returned event. Getting that last step wrong compiles cleanly and fails only when the buffer changes.

Predict and run

Predict before running C++
#include <iostream>
#include <string>
#include <string_view>

std::string owned_suffix(std::string_view text) {
    auto separator = text.find('|');
    if (separator == std::string_view::npos) { return {}; }
    return std::string(text.substr(separator + 1));
}

int main() {
    std::string result = owned_suffix(std::string("rename|Bolts"));
    std::cout << result << "\n";
    return 0;
}
Check your prediction
Text
Bolts

The argument is a temporary std::string, which lives until the end of the full expression, the whole initialization of result. During the call, text and text.substr(...) are views into it, and std::string(...) copies the characters out before the temporary dies. Change the return type to std::string_view and remove the conversion, and main no longer compiles: building a std::string from a view needs an explicit conversion. Make it compile the tempting way, std::string_view result = ..., and now result is a view into a temporary that died at the end of that statement, so printing it is undefined behavior. (Writing std::string result{owned_suffix(...)} instead would be safe, because the copy happens before the temporary dies.) Clang may warn about some cases like this; it cannot warn about all of them.

Splitting into views

find and substr on a std::string_view return positions and smaller views, never copies:

Fields as views into one line C++
#include <iostream>
#include <string_view>
#include <vector>

std::vector<std::string_view> split(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) { return fields; }
        start = end + 1;
    }
}

int main() {
    for (std::string_view line : {"adjust|2|-3", "rename|2|", "create"}) {
        const auto fields = split(line);
        std::cout << fields.size() << ":";
        for (std::string_view field : fields) { std::cout << " [" << field << "]"; }
        std::cout << "\n";
    }
    return 0;
}
Text
3: [adjust] [2] [-3]
3: [rename] [2] []
1: [create]

substr(start, npos) means "to the end", which handles the last field. A trailing | produces an empty final field rather than none, which is what lets rename|2| reach the name check and fail as an invalid name instead of slipping through as a two-field line. The returned vector of views is safe to use only while line's characters live; here they are string literals, which live for the whole program. The project's parser also stops after four fields, so a hostile line with thousands of separators cannot make it build a huge vector.

Numbers without exceptions

std::stoi reports errors by throwing, which this course cannot use. std::from_chars, from <charconv>, reports them through its return value, ignores locales, and tells you where it stopped, so you can insist that the whole field is a number:

Strict integer parsing C++
#include <charconv>
#include <iostream>
#include <optional>
#include <string_view>

std::optional<int> parse_int(std::string_view text) {
    int value = 0;
    const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
    if (error != std::errc{} || end != text.data() + text.size()) { return std::nullopt; }
    return value;
}

int main() {
    for (std::string_view text : {"42", "-7", "+1", " 4", "4x", "", "99999999999"}) {
        const auto value = parse_int(text);
        std::cout << "[" << text << "] " << (value ? std::to_string(*value) : "rejected") << "\n";
    }
    return 0;
}
Text
[42] 42
[-7] -7
[+1] rejected
[ 4] rejected
[4x] rejected
[] rejected
[99999999999] rejected

from_chars rejects a leading + and leading whitespace, and reports std::errc::result_out_of_range for a value too large for int, without undefined behavior. The end check rejects 4x, which would otherwise parse as 4. The project's number helper reaches the same results a different way, by checking that every character is a digit, allowing a leading minus for deltas, before converting with a string stream; either approach is fine as long as tests pin down the edge cases.

Which errors belong to the parser

ParseResult is std::variant<Event, ParseError>: the parser returns a typed event or a reason. It rejects what the text alone can prove wrong: unknown kinds, wrong field counts, non-numeric fields, IDs outside 1..9999, quantities outside 0..1000, invalid names. It cannot reject a duplicate Create or an Adjust of a missing item, because that depends on the inventory, which the parser never sees. Those are the engine's errors, reported with an index during apply. Keeping the boundary clean means the parser is a pure function of its input, easy to test line by line.

Practice

Exercise

Your turn

Write std::variant<Adjust, ParseError> parse_adjust(std::string_view line) for lines of the form adjust|id|delta. Require exactly three fields, the word adjust, an ID in 1..9999 and a delta in -1000..1000, parsed strictly with from_chars. Print each result:

Shell
adjust|2|-3 -> Adjust 2 -3
adjust|2 -> error: field count
adjust|0|5 -> error: invalid id
adjust|2|+3 -> error: invalid delta
adjust|2|5000 -> error: invalid delta
create|2|5 -> error: not an adjustment
Your workspace C++
#include <charconv>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <variant>
#include <vector>

struct Adjust { int id; int delta; };
struct ParseError { std::string message; };

int main() {
    for (std::string_view line : {"adjust|2|-3", "adjust|2", "adjust|0|5", "adjust|2|+3", "adjust|2|5000", "create|2|5"}) {
        // Parse the line and print the result.
        (void)line;
    }
    return 0;
}
Hint 1: the idea

Split into views, check the shape, then convert and range-check each number. Only the error message needs to be owned.

Hint 2: a first step

Reuse split and parse_int from the lesson, then start with if (fields.size() != 3) { return ParseError{"field count"}; }.

Show one solution
Run the solution C++
#include <charconv>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <variant>
#include <vector>

struct Adjust { int id; int delta; };
struct ParseError { std::string message; };

std::vector<std::string_view> split(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) { return fields; }
        start = end + 1;
    }
}

std::optional<int> parse_int(std::string_view text) {
    int value = 0;
    const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), value);
    if (error != std::errc{} || end != text.data() + text.size()) { return std::nullopt; }
    return value;
}

std::variant<Adjust, ParseError> parse_adjust(std::string_view line) {
    const auto fields = split(line);
    if (fields.size() != 3) { return ParseError{"field count"}; }
    if (fields[0] != "adjust") { return ParseError{"not an adjustment"}; }
    const auto id = parse_int(fields[1]);
    if (!id || *id < 1 || *id > 9999) { return ParseError{"invalid id"}; }
    const auto delta = parse_int(fields[2]);
    if (!delta || *delta < -1000 || *delta > 1000) { return ParseError{"invalid delta"}; }
    return Adjust{*id, *delta};
}

int main() {
    for (std::string_view line : {"adjust|2|-3", "adjust|2", "adjust|0|5", "adjust|2|+3", "adjust|2|5000", "create|2|5"}) {
        const auto result = parse_adjust(line);
        std::cout << line << " -> ";
        if (const auto* adjust = std::get_if<Adjust>(&result)) {
            std::cout << "Adjust " << adjust->id << " " << adjust->delta << "\n";
        } else {
            std::cout << "error: " << std::get<ParseError>(result).message << "\n";
        }
    }
    return 0;
}
Text
adjust|2|-3 -> Adjust 2 -3
adjust|2 -> error: field count
adjust|0|5 -> error: invalid id
adjust|2|+3 -> error: invalid delta
adjust|2|5000 -> error: invalid delta
create|2|5 -> error: not an adjustment

The returned Adjust holds only integers, and ParseError owns its message, so nothing returned points into line. The views in fields die with the function. The std::get<ParseError> is safe because the get_if just ruled out the only other alternative. Next you turn the other direction: from events back to text, in one canonical form that tests can compare exactly.

Was this article helpful?

Your response is saved on this device.