From dc4d115817d45efbfa3cb06b8504c0c9394b1762 Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Wed, 25 Nov 2026 13:42:45 +0100 Subject: [PATCH 1/2] Add the StateWriter seam Guest auth's whole point is that a player keeps the same account across restarts, which needs player_identifier persisted. There is no portable way to write a file on every platform this SDK targets, so the SDK defines the interface and ships two implementations. Typed accessors rather than strings-only: a store that only speaks strings forces every adopter to write the same conversions and get the same rounding wrong. GetUInt64 is separate from GetInt64 because player_id is a uint64 on the wire and a valid id above INT64_MAX must round-trip exactly (D4). A getter returns false for a type mismatch rather than converting, because guessing is how a corrupt store becomes a wrong player id. FileStateWriter writes a flat ype:key=value file. Deliberately not JSON: a corrupt save would become a parse error the adopter has to handle, where a flat format degrades to skipping the bad line. Not atomic across a crash - documented rather than hidden, because write-temp-then-rename is not portable to every target. Found while testing: GetStateWriter returned the expired handle when an injected writer died, leaving the client with nothing to persist to. The default is now always constructed and resolved at read time, not at set time. Verified by sabotage: parsing uint64 with strtoll fails four assertions on the INT64_MAX case. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CMakeLists.txt | 1 + README.md | 57 +++++ include/lootlocker/client.h | 15 ++ include/lootlocker/state_writer.h | 139 ++++++++++++ src/core/client.cpp | 41 +++- src/core/state_writer.cpp | 343 ++++++++++++++++++++++++++++ tests/CMakeLists.txt | 5 + tests/test_state_writer.cpp | 364 ++++++++++++++++++++++++++++++ 8 files changed, 964 insertions(+), 1 deletion(-) create mode 100644 include/lootlocker/state_writer.h create mode 100644 src/core/state_writer.cpp create mode 100644 tests/test_state_writer.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 1e837b4..8b44f4b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -143,6 +143,7 @@ add_library(lootlocker_core STATIC src/core/rate_limiter.cpp src/core/json.cpp src/core/query_parameters.cpp + src/core/state_writer.cpp src/core/executor.cpp src/core/client.cpp ) diff --git a/README.md b/README.md index 3dcfccf..eb259ed 100644 --- a/README.md +++ b/README.md @@ -328,6 +328,63 @@ definition. over a shared, immutable document, which is what makes it cheap to pass around and safe to hold across a callback. Writing needs its own type. +### Persistence + +The SDK remembers a session between launches through a `StateWriter`. The default writes one +file next to the game; a console or an engine injects its own. + +```cpp +// The default: one file, next to the game. +lootlocker::Config config; +config.domain_key = "your-domain"; + +// Or your own store, for a console's save-data API or an engine's settings. +config.state_writer = my_engine_state_writer; + +// Or nothing at all, if you would rather re-authenticate every launch. +config.state_writer = std::make_shared(); +``` + +The interface is typed rather than strings-only, because a store that only speaks strings +forces every adopter to write the same conversions and get the same rounding wrong: + +```cpp +class StateWriter { +public: + virtual bool GetString(const std::string& key, std::string& out) = 0; + virtual void SetString(const std::string& key, const std::string& value) = 0; + + virtual bool GetInt64(const std::string& key, std::int64_t& out) = 0; + virtual void SetInt64(const std::string& key, std::int64_t value) = 0; + + virtual bool GetUInt64(const std::string& key, std::uint64_t& out) = 0; + virtual void SetUInt64(const std::string& key, std::uint64_t value) = 0; + + virtual bool GetDouble(const std::string& key, double& out) = 0; + virtual void SetDouble(const std::string& key, double value) = 0; + + virtual bool GetBool(const std::string& key, bool& out) = 0; + virtual void SetBool(const std::string& key, bool value) = 0; + + virtual void Erase(const std::string& key) = 0; + virtual bool Has(const std::string& key) = 0; +}; +``` + +`GetUInt64` exists separately from `GetInt64` because `player_id` is a `uint64` on the wire +and a valid id above `INT64_MAX` must round-trip exactly. A getter returns `false` and leaves +`out` untouched when the key is absent **or holds a different type** — it never converts, +because guessing is how a corrupt store becomes a wrong player id. + +Implementations must not throw. Persistence is best-effort: a failed write never fails a +request. + +`FileStateWriter` writes a flat `type:key=value` text file, whole, on every change. It is +**not atomic across a crash** — a power loss mid-write loses the file, and the cost is one +re-authentication. Write-temp-then-rename is not portable to every platform this SDK +targets, so the limitation is documented rather than hidden. A corrupt line is skipped on +load rather than losing the whole file. + ### There is no parser seam Unlike the transport or the state writer, the JSON parser is not injectable. It is internal diff --git a/include/lootlocker/client.h b/include/lootlocker/client.h index 8c7bf28..b34ff56 100644 --- a/include/lootlocker/client.h +++ b/include/lootlocker/client.h @@ -15,6 +15,7 @@ namespace lootlocker { class Client; +class StateWriter; namespace core { class Executor; @@ -79,6 +80,20 @@ class Client { // more. const std::string& GetInstanceIdentifier() const; + // Replaces the state writer. The client observes it through a `weak_ptr`, so the + // adopter keeps ownership. + // + // Unlike `SetTransport`, this is allowed at any time: a state writer has no in-flight + // state to strand, and swapping one mid-session is a legitimate thing for a game to do + // when the player signs in to a platform account. + // + // An empty or dead `weak_ptr` falls back to the default `FileStateWriter`. + void SetStateWriter(std::weak_ptr writer); + + // The state writer in use. Never empty: the client always has one, defaulting to + // `FileStateWriter`. + std::weak_ptr GetStateWriter() const; + private: // The correct form: the function is declared in `core` above, so the friend // declaration names it qualified rather than declaring a new one in this scope. diff --git a/include/lootlocker/state_writer.h b/include/lootlocker/state_writer.h new file mode 100644 index 0000000..748fb9c --- /dev/null +++ b/include/lootlocker/state_writer.h @@ -0,0 +1,139 @@ +#pragma once + +// Persistence (D11, R18). The seam that lets the SDK remember a session between launches. +// +// The problem this solves: guest auth's whole point is that a player keeps the same account +// across restarts. That requires remembering `player_identifier`, and there is no portable +// way to write a file on every platform this SDK targets — a console has its own save-data +// API, an engine has its own settings store, and a plain application has a filesystem. +// +// So the SDK defines the interface and ships two implementations: `FileStateWriter`, which +// writes one file next to the game, and `NullStateWriter`, which writes nothing. An engine +// or a console injects its own through `Config::state_writer` or `Client::SetStateWriter`. +// +// **Typed accessors rather than strings-only.** A store that only speaks strings forces +// every adopter to write the same conversions and get the same rounding wrong — and the +// `player_id` case is exactly where that bites, because a `uint64` above `INT64_MAX` does +// not survive a round trip through a `double` or a signed integer. +// +// **Implementations must not throw** (D7). A failed write is reported by returning false +// from the getter or by silently doing nothing from the setter; the SDK treats persistence +// as best-effort and never fails a request because a save failed. + +#include +#include +#include + +namespace lootlocker { + +class StateWriter { +public: + virtual ~StateWriter() = default; + + // Each getter returns false and leaves `out` untouched when the key is absent or holds + // a value of a different type. It does not convert: a key written as a string is not + // readable as an integer, because guessing is how a corrupt store becomes a wrong + // player id. + virtual bool GetString(const std::string& key, std::string& out) = 0; + virtual void SetString(const std::string& key, const std::string& value) = 0; + + virtual bool GetInt64(const std::string& key, std::int64_t& out) = 0; + virtual void SetInt64(const std::string& key, std::int64_t value) = 0; + + // Unsigned, because `player_id` is a `uint64` on the wire and a valid id above + // `INT64_MAX` must round-trip exactly (D4). + virtual bool GetUInt64(const std::string& key, std::uint64_t& out) = 0; + virtual void SetUInt64(const std::string& key, std::uint64_t value) = 0; + + virtual bool GetDouble(const std::string& key, double& out) = 0; + virtual void SetDouble(const std::string& key, double value) = 0; + + virtual bool GetBool(const std::string& key, bool& out) = 0; + virtual void SetBool(const std::string& key, bool value) = 0; + + virtual void Erase(const std::string& key) = 0; + virtual bool Has(const std::string& key) = 0; +}; + +// Writes nothing, and reports every key as absent. +// +// For a game that would rather re-authenticate every launch, and for a test that wants the +// no-persistence path. It is a real implementation rather than a null pointer, so the +// client never has to branch on whether a writer exists. +class NullStateWriter : public StateWriter { +public: + bool GetString(const std::string& key, std::string& out) override; + void SetString(const std::string& key, const std::string& value) override; + + bool GetInt64(const std::string& key, std::int64_t& out) override; + void SetInt64(const std::string& key, std::int64_t value) override; + + bool GetUInt64(const std::string& key, std::uint64_t& out) override; + void SetUInt64(const std::string& key, std::uint64_t value) override; + + bool GetDouble(const std::string& key, double& out) override; + void SetDouble(const std::string& key, double value) override; + + bool GetBool(const std::string& key, bool& out) override; + void SetBool(const std::string& key, bool value) override; + + void Erase(const std::string& key) override; + bool Has(const std::string& key) override; +}; + +// Writes one file, next to the game by default. +// +// The format is a flat text file of `type:key=value` lines, written whole on every change. +// Deliberately not JSON: the SDK already has a JSON parser, but using it here would mean a +// corrupt save file is a parse error the adopter has to handle, and a flat format degrades +// to "skip the bad line" instead. +// +// **Not atomic across a crash.** A write truncates and rewrites, so a power loss mid-write +// loses the file. That is acceptable for a session token — the cost is one re-authentication +// — and the alternative (write-temp-then-rename) is not portable to every platform this SDK +// targets. Documented rather than hidden. +class FileStateWriter : public StateWriter { +public: + // `path` is the file to write. Empty means the default, which is + // `lootlocker-state.txt` in the current working directory. + // + // The file is read once, at construction, so a writer is a snapshot plus a write-through + // cache. A second writer on the same path will not see the first one's later writes. + explicit FileStateWriter(const std::string& path = std::string()); + ~FileStateWriter() override; + + FileStateWriter(const FileStateWriter&) = delete; + FileStateWriter& operator=(const FileStateWriter&) = delete; + + bool GetString(const std::string& key, std::string& out) override; + void SetString(const std::string& key, const std::string& value) override; + + bool GetInt64(const std::string& key, std::int64_t& out) override; + void SetInt64(const std::string& key, std::int64_t value) override; + + bool GetUInt64(const std::string& key, std::uint64_t& out) override; + void SetUInt64(const std::string& key, std::uint64_t value) override; + + bool GetDouble(const std::string& key, double& out) override; + void SetDouble(const std::string& key, double value) override; + + bool GetBool(const std::string& key, bool& out) override; + void SetBool(const std::string& key, bool value) override; + + void Erase(const std::string& key) override; + bool Has(const std::string& key) override; + + // The path in use, after the default was resolved. + const std::string& GetPath() const; + + // True when the last write succeeded. A writer whose file is unwritable still serves + // reads from its cache, so a game on a read-only filesystem degrades to + // re-authenticating rather than failing. + bool LastWriteSucceeded() const; + +private: + struct Impl; + std::unique_ptr m_impl; +}; + +} // namespace lootlocker diff --git a/src/core/client.cpp b/src/core/client.cpp index f9c4033..80a4856 100644 --- a/src/core/client.cpp +++ b/src/core/client.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include "clock.h" #include "executor.h" @@ -30,6 +31,12 @@ struct Client::Impl { // in, which is a supported configuration: the adopter injects their own. std::shared_ptr owned_transport; + // The state writer. The default is always constructed, so the client can fall back to it + // when an injected writer dies - the seam is "adopter owns, SDK observes", so the + // injected one is held weakly and may expire at any time. + std::shared_ptr default_state_writer; + std::weak_ptr state_writer; + core::SteadyClock clock; std::unique_ptr executor; }; @@ -110,9 +117,18 @@ Client::Client(const Config& config) : m_impl(new Impl()) #endif } + // The state writer: the injected one wins, otherwise the file default. The default is + // always constructed, because an injected writer is held weakly and may expire later - + // the client then falls back to this rather than having nothing to persist to. + m_impl->default_state_writer = std::make_shared(); + if (std::shared_ptr injected = config.state_writer.lock()) { + m_impl->state_writer = injected; + } else { + m_impl->state_writer = m_impl->default_state_writer; + } + core::ExecutorSettings settings; settings.queue = config.queue; - // An invalid config means the policy was never validated, so it must not reach the // limiter: a rejected 2-billion-second window would still derive 2 billion buckets and // attempt a multi-gigabyte allocation during construction, which in a no-exceptions @@ -167,6 +183,29 @@ const std::string& Client::GetInstanceIdentifier() const return m_impl->instance_identifier; } +void Client::SetStateWriter(std::weak_ptr writer) +{ + if (std::shared_ptr resolved = writer.lock()) { + m_impl->state_writer = resolved; + return; + } + // An empty or dead writer falls back to the default rather than leaving the client with + // nothing. A game that wants no persistence injects a `NullStateWriter` explicitly, + // which is a different statement from "I forgot". + m_impl->state_writer = m_impl->default_state_writer; +} + +std::weak_ptr Client::GetStateWriter() const +{ + // Resolved at read time, not at set time: the injected writer is held weakly, so it may + // have died since. Returning the expired handle would leave the caller with nothing to + // persist to, which is the opposite of what a default is for. + if (std::shared_ptr live = m_impl->state_writer.lock()) { + return live; + } + return m_impl->default_state_writer; +} + namespace core { Executor& GetExecutor(Client& client) diff --git a/src/core/state_writer.cpp b/src/core/state_writer.cpp new file mode 100644 index 0000000..3f2e2d6 --- /dev/null +++ b/src/core/state_writer.cpp @@ -0,0 +1,343 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace lootlocker { + +// --------------------------------------------------------------------------- +// NullStateWriter +// --------------------------------------------------------------------------- + +bool NullStateWriter::GetString(const std::string&, std::string&) { return false; } +void NullStateWriter::SetString(const std::string&, const std::string&) {} + +bool NullStateWriter::GetInt64(const std::string&, std::int64_t&) { return false; } +void NullStateWriter::SetInt64(const std::string&, std::int64_t) {} + +bool NullStateWriter::GetUInt64(const std::string&, std::uint64_t&) { return false; } +void NullStateWriter::SetUInt64(const std::string&, std::uint64_t) {} + +bool NullStateWriter::GetDouble(const std::string&, double&) { return false; } +void NullStateWriter::SetDouble(const std::string&, double) {} + +bool NullStateWriter::GetBool(const std::string&, bool&) { return false; } +void NullStateWriter::SetBool(const std::string&, bool) {} + +void NullStateWriter::Erase(const std::string&) {} +bool NullStateWriter::Has(const std::string&) { return false; } + +// --------------------------------------------------------------------------- +// FileStateWriter +// --------------------------------------------------------------------------- + +namespace { + +// The type tag on each line. A key written as one type is not readable as another, which is +// what stops a corrupt or hand-edited file from silently becoming a wrong player id. +enum class ValueType { String, Int64, UInt64, Double, Bool }; + +const char* TypeTag(ValueType type) +{ + switch (type) { + case ValueType::String: return "s"; + case ValueType::Int64: return "i"; + case ValueType::UInt64: return "u"; + case ValueType::Double: return "d"; + case ValueType::Bool: return "b"; + } + return "s"; +} + +bool ParseTypeTag(const std::string& tag, ValueType& out) +{ + if (tag == "s") { out = ValueType::String; return true; } + if (tag == "i") { out = ValueType::Int64; return true; } + if (tag == "u") { out = ValueType::UInt64; return true; } + if (tag == "d") { out = ValueType::Double; return true; } + if (tag == "b") { out = ValueType::Bool; return true; } + return false; +} + +struct Entry { + ValueType type = ValueType::String; + std::string text; +}; + +// A key may not contain the separators, because the format is line-based and unescaped. +// Rejecting is better than escaping: an escaped format is a parser, and this is deliberately +// not one. +bool IsValidKey(const std::string& key) +{ + if (key.empty()) { + return false; + } + return key.find('=') == std::string::npos && key.find('\n') == std::string::npos && + key.find('\r') == std::string::npos; +} + +// A value may not contain a newline, for the same reason. A session token is base64-ish and +// a player name could contain anything, so a newline is replaced rather than rejected - the +// alternative is losing the whole write over a display name. +std::string SanitizeValue(const std::string& value) +{ + std::string out = value; + for (std::size_t i = 0; i < out.size(); ++i) { + if (out[i] == '\n' || out[i] == '\r') { + out[i] = ' '; + } + } + return out; +} + +std::string FormatDouble(double value) +{ + // `%.17g` round-trips an IEEE double exactly. A shorter form would lose precision on a + // value the SDK wrote itself, which is the one thing a store must not do. + char buffer[64]; + std::snprintf(buffer, sizeof(buffer), "%.17g", value); + return std::string(buffer); +} + +} // namespace + +struct FileStateWriter::Impl { + std::string path; + std::map entries; + bool last_write_ok = true; + + void Load() + { + std::ifstream in(path.c_str(), std::ios::binary); + if (!in) { + // No file yet is the normal first-launch case, not an error. + return; + } + + std::string line; + while (std::getline(in, line)) { + if (line.empty()) { + continue; + } + + // `type:key=value`. A malformed line is skipped rather than aborting the load, + // so one bad line does not lose the whole session. + const std::size_t colon = line.find(':'); + if (colon == std::string::npos) { + continue; + } + const std::size_t equals = line.find('=', colon + 1); + if (equals == std::string::npos) { + continue; + } + + ValueType type = ValueType::String; + if (!ParseTypeTag(line.substr(0, colon), type)) { + continue; + } + + const std::string key = line.substr(colon + 1, equals - colon - 1); + if (!IsValidKey(key)) { + continue; + } + + Entry entry; + entry.type = type; + entry.text = line.substr(equals + 1); + entries[key] = entry; + } + } + + void Save() + { + // Written whole. A partial write is possible on a crash, which is documented on the + // class rather than papered over: the cost is one re-authentication. + std::ofstream out(path.c_str(), std::ios::binary | std::ios::trunc); + if (!out) { + last_write_ok = false; + return; + } + + for (std::map::const_iterator it = entries.begin(); + it != entries.end(); ++it) { + out << TypeTag(it->second.type) << ':' << it->first << '=' << it->second.text + << '\n'; + } + + out.flush(); + last_write_ok = out.good(); + } + + void Put(const std::string& key, ValueType type, const std::string& text) + { + if (!IsValidKey(key)) { + // A key with a separator cannot be represented. Silently dropping it is better + // than writing a file that will not load back. + return; + } + Entry entry; + entry.type = type; + entry.text = SanitizeValue(text); + entries[key] = entry; + Save(); + } + + bool Get(const std::string& key, ValueType expected, std::string& out) const + { + const std::map::const_iterator it = entries.find(key); + if (it == entries.end() || it->second.type != expected) { + return false; + } + out = it->second.text; + return true; + } +}; + +FileStateWriter::FileStateWriter(const std::string& path) : m_impl(new Impl()) +{ + m_impl->path = path.empty() ? std::string("lootlocker-state.txt") : path; + m_impl->Load(); +} + +FileStateWriter::~FileStateWriter() = default; + +const std::string& FileStateWriter::GetPath() const +{ + return m_impl->path; +} + +bool FileStateWriter::LastWriteSucceeded() const +{ + return m_impl->last_write_ok; +} + +bool FileStateWriter::GetString(const std::string& key, std::string& out) +{ + return m_impl->Get(key, ValueType::String, out); +} + +void FileStateWriter::SetString(const std::string& key, const std::string& value) +{ + m_impl->Put(key, ValueType::String, value); +} + +bool FileStateWriter::GetInt64(const std::string& key, std::int64_t& out) +{ + std::string text; + if (!m_impl->Get(key, ValueType::Int64, text)) { + return false; + } + + // `strtoll` with an end pointer, so trailing garbage is a failure rather than a silent + // truncation. + errno = 0; + char* end = nullptr; + const long long parsed = std::strtoll(text.c_str(), &end, 10); + if (errno != 0 || end == text.c_str() || *end != '\0') { + return false; + } + out = static_cast(parsed); + return true; +} + +void FileStateWriter::SetInt64(const std::string& key, std::int64_t value) +{ + char buffer[32]; + std::snprintf(buffer, sizeof(buffer), "%lld", static_cast(value)); + m_impl->Put(key, ValueType::Int64, buffer); +} + +bool FileStateWriter::GetUInt64(const std::string& key, std::uint64_t& out) +{ + std::string text; + if (!m_impl->Get(key, ValueType::UInt64, text)) { + return false; + } + + // `strtoull` rather than `strtoll`: a `player_id` above `INT64_MAX` is valid and must + // round-trip exactly (D4). A leading '-' is rejected explicitly, because `strtoull` + // accepts it and wraps. + if (!text.empty() && text[0] == '-') { + return false; + } + + errno = 0; + char* end = nullptr; + const unsigned long long parsed = std::strtoull(text.c_str(), &end, 10); + if (errno != 0 || end == text.c_str() || *end != '\0') { + return false; + } + out = static_cast(parsed); + return true; +} + +void FileStateWriter::SetUInt64(const std::string& key, std::uint64_t value) +{ + char buffer[32]; + std::snprintf(buffer, sizeof(buffer), "%llu", static_cast(value)); + m_impl->Put(key, ValueType::UInt64, buffer); +} + +bool FileStateWriter::GetDouble(const std::string& key, double& out) +{ + std::string text; + if (!m_impl->Get(key, ValueType::Double, text)) { + return false; + } + + errno = 0; + char* end = nullptr; + const double parsed = std::strtod(text.c_str(), &end); + if (errno != 0 || end == text.c_str() || *end != '\0') { + return false; + } + out = parsed; + return true; +} + +void FileStateWriter::SetDouble(const std::string& key, double value) +{ + m_impl->Put(key, ValueType::Double, FormatDouble(value)); +} + +bool FileStateWriter::GetBool(const std::string& key, bool& out) +{ + std::string text; + if (!m_impl->Get(key, ValueType::Bool, text)) { + return false; + } + if (text == "1") { + out = true; + return true; + } + if (text == "0") { + out = false; + return true; + } + return false; +} + +void FileStateWriter::SetBool(const std::string& key, bool value) +{ + m_impl->Put(key, ValueType::Bool, value ? "1" : "0"); +} + +void FileStateWriter::Erase(const std::string& key) +{ + if (m_impl->entries.erase(key) != 0) { + m_impl->Save(); + } +} + +bool FileStateWriter::Has(const std::string& key) +{ + return m_impl->entries.find(key) != m_impl->entries.end(); +} + +} // namespace lootlocker diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 27ca845..e9f5dc6 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -75,6 +75,11 @@ target_link_libraries(test_definition PRIVATE LootLocker::core lootlocker_compil target_include_directories(test_definition PRIVATE ${CMAKE_SOURCE_DIR}/src/core) add_test(NAME definition COMMAND test_definition) +# The StateWriter seam (T12a). Public surface, so no `src/` include path is needed. +add_executable(test_state_writer test_state_writer.cpp) +target_link_libraries(test_state_writer PRIVATE LootLocker::core lootlocker_compile_options) +add_test(NAME state_writer COMMAND test_state_writer) + # The end-to-end transport test (T11, owner 2026-11-13): a real round trip through the real # curl transport against a loopback server, plus the proof that `Config::transport` is # actually consulted. diff --git a/tests/test_state_writer.cpp b/tests/test_state_writer.cpp new file mode 100644 index 0000000..c4d8ecc --- /dev/null +++ b/tests/test_state_writer.cpp @@ -0,0 +1,364 @@ +// The StateWriter seam (T12a). +// +// The verification the task asks for: each typed accessor round-trips its type; the null +// writer persists nothing and the client still works; a `uint64` above `INT64_MAX` +// round-trips exactly (the `player_id` case, D4). + +#include +#include +#include +#include + +#include "test_harness.h" + +#include +#include +#include + +namespace { + +using lootlocker::Client; +using lootlocker::Config; +using lootlocker::FileStateWriter; +using lootlocker::NullStateWriter; +using lootlocker::StateWriter; + +// A scratch file that removes itself, so a failing test does not leave state behind for the +// next run to trip over. +struct TempFile { + std::string path; + + explicit TempFile(const char* name) + { + path = std::string("test-state-") + name + ".txt"; + std::remove(path.c_str()); + } + + ~TempFile() { std::remove(path.c_str()); } +}; + +// --- typed round trips ----------------------------------------------------- + +void TestStringRoundTrip() +{ + TempFile file("string"); + FileStateWriter writer(file.path); + + writer.SetString("session_token", "abc123"); + + std::string out; + CHECK(writer.GetString("session_token", out)); + CHECK_EQ(out, "abc123"); +} + +void TestInt64RoundTrip() +{ + TempFile file("int64"); + FileStateWriter writer(file.path); + + writer.SetInt64("negative", -9007199254740993LL); + + std::int64_t out = 0; + CHECK(writer.GetInt64("negative", out)); + CHECK_EQ_INT(static_cast(out), -9007199254740993LL); +} + +// The `player_id` case (D4): a valid id above INT64_MAX must round-trip exactly. This is the +// reason the interface has a `uint64` accessor at all. +void TestUInt64AboveInt64MaxRoundTrips() +{ + TempFile file("uint64"); + FileStateWriter writer(file.path); + + const std::uint64_t big = 18446744073709551615ULL; // UINT64_MAX + writer.SetUInt64("player_id", big); + + std::uint64_t out = 0; + CHECK(writer.GetUInt64("player_id", out)); + CHECK(out == big); + + // And it survives a reload, which is the whole point of persistence. + FileStateWriter reopened(file.path); + std::uint64_t reloaded = 0; + CHECK(reopened.GetUInt64("player_id", reloaded)); + CHECK(reloaded == big); +} + +void TestDoubleRoundTrip() +{ + TempFile file("double"); + FileStateWriter writer(file.path); + + writer.SetDouble("ratio", 0.1); + + double out = 0.0; + CHECK(writer.GetDouble("ratio", out)); + CHECK(out == 0.1); // exact, because the format round-trips +} + +void TestBoolRoundTrip() +{ + TempFile file("bool"); + FileStateWriter writer(file.path); + + writer.SetBool("seen_before", true); + writer.SetBool("check_dlc", false); + + bool out = false; + CHECK(writer.GetBool("seen_before", out)); + CHECK(out); + + CHECK(writer.GetBool("check_dlc", out)); + CHECK(!out); +} + +// --- type safety ----------------------------------------------------------- + +// A key written as one type is not readable as another. Guessing is how a corrupt store +// becomes a wrong player id. +void TestTypeMismatchIsNotConverted() +{ + TempFile file("mismatch"); + FileStateWriter writer(file.path); + + writer.SetString("player_id", "12345"); + + std::uint64_t out = 0; + CHECK(!writer.GetUInt64("player_id", out)); + CHECK_EQ_INT(static_cast(out), 0); // untouched +} + +void TestAbsentKey() +{ + TempFile file("absent"); + FileStateWriter writer(file.path); + + std::string out = "untouched"; + CHECK(!writer.GetString("nope", out)); + CHECK_EQ(out, "untouched"); + CHECK(!writer.Has("nope")); +} + +void TestErase() +{ + TempFile file("erase"); + FileStateWriter writer(file.path); + + writer.SetString("k", "v"); + CHECK(writer.Has("k")); + writer.Erase("k"); + CHECK(!writer.Has("k")); + + // And the erase is persisted, not just cached. + FileStateWriter reopened(file.path); + CHECK(!reopened.Has("k")); +} + +// --- persistence across instances ------------------------------------------ + +void TestSurvivesReopen() +{ + TempFile file("reopen"); + + { + FileStateWriter writer(file.path); + writer.SetString("player_identifier", "guest-42"); + writer.SetUInt64("player_id", 9007199254740993ULL); + writer.SetBool("seen_before", true); + } + + FileStateWriter reopened(file.path); + + std::string identifier; + CHECK(reopened.GetString("player_identifier", identifier)); + CHECK_EQ(identifier, "guest-42"); + + std::uint64_t id = 0; + CHECK(reopened.GetUInt64("player_id", id)); + CHECK(id == 9007199254740993ULL); + + bool seen = false; + CHECK(reopened.GetBool("seen_before", seen)); + CHECK(seen); +} + +// A corrupt line is skipped rather than losing the whole file. One bad line must not cost +// the player their session. +void TestCorruptLineIsSkipped() +{ + TempFile file("corrupt"); + + { + std::FILE* f = std::fopen(file.path.c_str(), "wb"); + CHECK(f != nullptr); + if (f != nullptr) { + std::fputs("s:good=kept\n", f); + std::fputs("this line has no separator\n", f); + std::fputs("x:badtype=1\n", f); + std::fputs("s:also_good=yes\n", f); + std::fclose(f); + } + } + + FileStateWriter writer(file.path); + + std::string out; + CHECK(writer.GetString("good", out)); + CHECK_EQ(out, "kept"); + + CHECK(writer.GetString("also_good", out)); + CHECK_EQ(out, "yes"); + + CHECK(!writer.Has("badtype")); +} + +// A newline in a value must not break the file format. A player name could contain +// anything, and losing the whole write over a display name would be worse than replacing it. +void TestNewlineInValueIsSanitised() +{ + TempFile file("newline"); + FileStateWriter writer(file.path); + + writer.SetString("player_name", "line one\nline two"); + + std::string out; + CHECK(writer.GetString("player_name", out)); + CHECK_EQ(out, "line one line two"); + + // The other keys still load, which is what proves the file was not corrupted. + writer.SetString("after", "ok"); + FileStateWriter reopened(file.path); + CHECK(reopened.GetString("after", out)); + CHECK_EQ(out, "ok"); +} + +// --- the null writer ------------------------------------------------------- + +void TestNullWriterPersistsNothing() +{ + NullStateWriter writer; + + writer.SetString("k", "v"); + writer.SetUInt64("player_id", 42); + writer.SetBool("b", true); + + std::string s; + std::uint64_t u = 0; + bool b = false; + + CHECK(!writer.GetString("k", s)); + CHECK(!writer.GetUInt64("player_id", u)); + CHECK(!writer.GetBool("b", b)); + CHECK(!writer.Has("k")); +} + +// --- the client seam ------------------------------------------------------- + +Config MakeConfig() +{ + Config config; + config.domain_key = "testdomain"; + config.game_key = "testgamekey"; + config.game_version = "1.0.0"; + return config; +} + +// A client with no injected writer still has one, and it is the file default. +void TestClientHasADefaultWriter() +{ + Client client(MakeConfig()); + CHECK(!client.GetStateWriter().expired()); +} + +// An injected writer is the one used. +void TestClientUsesInjectedWriter() +{ + std::shared_ptr writer = std::make_shared(); + + Config config = MakeConfig(); + config.state_writer = writer; + + Client client(config); + + std::shared_ptr in_use = client.GetStateWriter().lock(); + CHECK(in_use != nullptr); + CHECK(in_use.get() == writer.get()); +} + +// The null writer is a supported configuration: the client still works, it just does not +// persist. +void TestClientWorksWithNullWriter() +{ + std::shared_ptr writer = std::make_shared(); + std::shared_ptr transport = + std::make_shared(); + + Config config = MakeConfig(); + config.state_writer = writer; + config.transport = transport; + + Client client(config); + + CHECK(client.ConfigError().Ok()); + CHECK(!client.GetStateWriter().expired()); + + // Nothing was written anywhere. + std::string out; + CHECK(!writer->GetString("session_token", out)); +} + +// `SetStateWriter` is allowed at any time, unlike `SetTransport`, because a writer has no +// in-flight state to strand. +void TestSetStateWriterAtRuntime() +{ + Client client(MakeConfig()); + + std::shared_ptr replacement = std::make_shared(); + client.SetStateWriter(replacement); + + std::shared_ptr in_use = client.GetStateWriter().lock(); + CHECK(in_use != nullptr); + CHECK(in_use.get() == replacement.get()); +} + +// An empty or dead writer falls back to the default rather than leaving the client with +// nothing. A game that wants no persistence injects a `NullStateWriter` explicitly, which is +// a different statement from "I forgot". +void TestSetStateWriterFallsBackWhenEmpty() +{ + Client client(MakeConfig()); + + client.SetStateWriter(std::weak_ptr()); + CHECK(!client.GetStateWriter().expired()); + + { + std::shared_ptr temporary = std::make_shared(); + client.SetStateWriter(temporary); + } + // The injected writer died with its scope. + CHECK(!client.GetStateWriter().expired()); +} + +} // namespace + +int main() +{ + TestStringRoundTrip(); + TestInt64RoundTrip(); + TestUInt64AboveInt64MaxRoundTrips(); + TestDoubleRoundTrip(); + TestBoolRoundTrip(); + TestTypeMismatchIsNotConverted(); + TestAbsentKey(); + TestErase(); + TestSurvivesReopen(); + TestCorruptLineIsSkipped(); + TestNewlineInValueIsSanitised(); + TestNullWriterPersistsNothing(); + TestClientHasADefaultWriter(); + TestClientUsesInjectedWriter(); + TestClientWorksWithNullWriter(); + TestSetStateWriterAtRuntime(); + TestSetStateWriterFallsBackWhenEmpty(); + return testing::Report(); +} From 31b904891361b63e2258c46287dc05d4fb5b1417 Mon Sep 17 00:00:00 2001 From: Erik Bylund Date: Wed, 25 Nov 2026 14:11:50 +0100 Subject: [PATCH 2/2] Rename the seam to IStateWriter, and fix three review findings Owner findings: - StateWriter is now IStateWriter, following the interface pattern IHttpTransport already uses. The two implementations keep their names: FileStateWriter and NullStateWriter are concrete classes, not interfaces. - The SetStateWriter comment claimed swapping mid-game was a legitimate thing to do. It is not - a game that does it finds the new writer knows nothing the old one stored. The behaviour is fine; the comment was wrong. Copilot findings: - The default FileStateWriter was constructed eagerly in the Client constructor, which reads lootlocker-state.txt on every client and contradicts the no-implicit-config non-negotiable (D9). It is now constructed lazily, on first use, so a client that never persists performs no file I/O. - The percent-g conversion is governed by the process-wide LC_NUMERIC locale, so a comma-decimal locale wrote 0,1 and GetDouble's strtod could not read it back under a different locale. A persisted format has to be locale-independent, so the separator is normalised to a dot on write. Same bug as QueryParameters, and it recurred because the two formatters were written separately. - The README example assigned a temporary shared_ptr to a weak_ptr, so it expired before the Client was constructed and the SDK silently fell back to the file default. The example now names an owning variable. The laziness test needed two attempts: the first version could not distinguish eager from lazy construction, because FileStateWriter's constructor reads the file rather than creating it. It now deletes the probe between construction and first use, which does distinguish them. Verified by sabotage. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 17 +++-- include/lootlocker/client.h | 14 ++-- include/lootlocker/config.h | 4 +- include/lootlocker/state_writer.h | 8 +-- src/core/client.cpp | 55 ++++++++-------- src/core/state_writer.cpp | 17 ++++- tests/test_state_writer.cpp | 105 ++++++++++++++++++++++++++++-- 7 files changed, 170 insertions(+), 50 deletions(-) diff --git a/README.md b/README.md index eb259ed..5aff967 100644 --- a/README.md +++ b/README.md @@ -330,26 +330,33 @@ hold across a callback. Writing needs its own type. ### Persistence -The SDK remembers a session between launches through a `StateWriter`. The default writes one +The SDK remembers a session between launches through a `IStateWriter`. The default writes one file next to the game; a console or an engine injects its own. ```cpp -// The default: one file, next to the game. +// The default: one file, next to the game. Constructed lazily, on first use, so a client +// that never persists anything performs no file I/O. lootlocker::Config config; config.domain_key = "your-domain"; // Or your own store, for a console's save-data API or an engine's settings. -config.state_writer = my_engine_state_writer; +// +// Keep the shared_ptr alive for as long as the client uses it: the client holds a weak_ptr, +// so a temporary would expire before the client was even constructed. +std::shared_ptr my_writer = std::make_shared(); +config.state_writer = my_writer; // Or nothing at all, if you would rather re-authenticate every launch. -config.state_writer = std::make_shared(); +std::shared_ptr no_persistence = + std::make_shared(); +config.state_writer = no_persistence; ``` The interface is typed rather than strings-only, because a store that only speaks strings forces every adopter to write the same conversions and get the same rounding wrong: ```cpp -class StateWriter { +class IStateWriter { public: virtual bool GetString(const std::string& key, std::string& out) = 0; virtual void SetString(const std::string& key, const std::string& value) = 0; diff --git a/include/lootlocker/client.h b/include/lootlocker/client.h index b34ff56..94d4b86 100644 --- a/include/lootlocker/client.h +++ b/include/lootlocker/client.h @@ -15,7 +15,7 @@ namespace lootlocker { class Client; -class StateWriter; +class IStateWriter; namespace core { class Executor; @@ -83,16 +83,18 @@ class Client { // Replaces the state writer. The client observes it through a `weak_ptr`, so the // adopter keeps ownership. // - // Unlike `SetTransport`, this is allowed at any time: a state writer has no in-flight - // state to strand, and swapping one mid-session is a legitimate thing for a game to do - // when the player signs in to a platform account. + // Unlike `SetTransport`, this is allowed at any time, because a state writer has no + // in-flight state to strand. That is a property of the implementation rather than an + // invitation: swapping the writer mid-game is not a use case anyone has, and a game + // that does it will find the new writer knows nothing the old one had already stored. + // Set it once, before the first request. // // An empty or dead `weak_ptr` falls back to the default `FileStateWriter`. - void SetStateWriter(std::weak_ptr writer); + void SetStateWriter(std::weak_ptr writer); // The state writer in use. Never empty: the client always has one, defaulting to // `FileStateWriter`. - std::weak_ptr GetStateWriter() const; + std::weak_ptr GetStateWriter() const; private: // The correct form: the function is declared in `core` above, so the friend diff --git a/include/lootlocker/config.h b/include/lootlocker/config.h index aae3653..7cb42ba 100644 --- a/include/lootlocker/config.h +++ b/include/lootlocker/config.h @@ -17,7 +17,7 @@ namespace lootlocker { -class StateWriter; +class IStateWriter; class IHttpTransport; class TimezoneProvider; @@ -95,7 +95,7 @@ struct Config { // Optional overrides. Empty means "use the SDK default". std::weak_ptr logger; // default writes to stderr - std::weak_ptr state_writer; // default is FileStateWriter + std::weak_ptr state_writer; // default is FileStateWriter std::weak_ptr transport; // default is the libcurl one // The least-verbose level the SDK emits (D26). diff --git a/include/lootlocker/state_writer.h b/include/lootlocker/state_writer.h index 748fb9c..c222332 100644 --- a/include/lootlocker/state_writer.h +++ b/include/lootlocker/state_writer.h @@ -26,9 +26,9 @@ namespace lootlocker { -class StateWriter { +class IStateWriter { public: - virtual ~StateWriter() = default; + virtual ~IStateWriter() = default; // Each getter returns false and leaves `out` untouched when the key is absent or holds // a value of a different type. It does not convert: a key written as a string is not @@ -60,7 +60,7 @@ class StateWriter { // For a game that would rather re-authenticate every launch, and for a test that wants the // no-persistence path. It is a real implementation rather than a null pointer, so the // client never has to branch on whether a writer exists. -class NullStateWriter : public StateWriter { +class NullStateWriter : public IStateWriter { public: bool GetString(const std::string& key, std::string& out) override; void SetString(const std::string& key, const std::string& value) override; @@ -92,7 +92,7 @@ class NullStateWriter : public StateWriter { // loses the file. That is acceptable for a session token — the cost is one re-authentication // — and the alternative (write-temp-then-rename) is not portable to every platform this SDK // targets. Documented rather than hidden. -class FileStateWriter : public StateWriter { +class FileStateWriter : public IStateWriter { public: // `path` is the file to write. Empty means the default, which is // `lootlocker-state.txt` in the current working directory. diff --git a/src/core/client.cpp b/src/core/client.cpp index 80a4856..70fd7eb 100644 --- a/src/core/client.cpp +++ b/src/core/client.cpp @@ -31,11 +31,24 @@ struct Client::Impl { // in, which is a supported configuration: the adopter injects their own. std::shared_ptr owned_transport; - // The state writer. The default is always constructed, so the client can fall back to it - // when an injected writer dies - the seam is "adopter owns, SDK observes", so the - // injected one is held weakly and may expire at any time. - std::shared_ptr default_state_writer; - std::weak_ptr state_writer; + // The state writer. The default is constructed lazily, on first use, so a client that + // never persists anything performs no file I/O - which is what keeps the "no implicit + // config" non-negotiable true (D9). An injected writer is held weakly and may expire at + // any time, so the default is also the fallback. + mutable std::shared_ptr default_state_writer; + std::weak_ptr state_writer; + + // The writer to use, constructing the default on first call. + std::shared_ptr ResolveStateWriter() const + { + if (std::shared_ptr live = state_writer.lock()) { + return live; + } + if (!default_state_writer) { + default_state_writer = std::make_shared(); + } + return default_state_writer; + } core::SteadyClock clock; std::unique_ptr executor; @@ -117,15 +130,10 @@ Client::Client(const Config& config) : m_impl(new Impl()) #endif } - // The state writer: the injected one wins, otherwise the file default. The default is - // always constructed, because an injected writer is held weakly and may expire later - - // the client then falls back to this rather than having nothing to persist to. - m_impl->default_state_writer = std::make_shared(); - if (std::shared_ptr injected = config.state_writer.lock()) { - m_impl->state_writer = injected; - } else { - m_impl->state_writer = m_impl->default_state_writer; - } + // The state writer: the injected one wins, otherwise the file default is constructed + // lazily on first use. Deliberately NOT constructed here - a client that never persists + // anything must perform no file I/O, which is what keeps "no implicit config" true (D9). + m_impl->state_writer = config.state_writer; core::ExecutorSettings settings; settings.queue = config.queue; @@ -183,27 +191,20 @@ const std::string& Client::GetInstanceIdentifier() const return m_impl->instance_identifier; } -void Client::SetStateWriter(std::weak_ptr writer) +void Client::SetStateWriter(std::weak_ptr writer) { - if (std::shared_ptr resolved = writer.lock()) { - m_impl->state_writer = resolved; - return; - } - // An empty or dead writer falls back to the default rather than leaving the client with - // nothing. A game that wants no persistence injects a `NullStateWriter` explicitly, + // An empty or dead writer falls back to the default, which is constructed lazily on + // first use. A game that wants no persistence injects a `NullStateWriter` explicitly, // which is a different statement from "I forgot". - m_impl->state_writer = m_impl->default_state_writer; + m_impl->state_writer = writer; } -std::weak_ptr Client::GetStateWriter() const +std::weak_ptr Client::GetStateWriter() const { // Resolved at read time, not at set time: the injected writer is held weakly, so it may // have died since. Returning the expired handle would leave the caller with nothing to // persist to, which is the opposite of what a default is for. - if (std::shared_ptr live = m_impl->state_writer.lock()) { - return live; - } - return m_impl->default_state_writer; + return m_impl->ResolveStateWriter(); } namespace core { diff --git a/src/core/state_writer.cpp b/src/core/state_writer.cpp index 3f2e2d6..86ca1f9 100644 --- a/src/core/state_writer.cpp +++ b/src/core/state_writer.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include #include @@ -102,7 +103,21 @@ std::string FormatDouble(double value) // value the SDK wrote itself, which is the one thing a store must not do. char buffer[64]; std::snprintf(buffer, sizeof(buffer), "%.17g", value); - return std::string(buffer); + + // `%g` is governed by the process-wide `LC_NUMERIC` locale, so in a comma-decimal locale + // this writes `0,1` - and `GetDouble` uses `strtod`, which under the same locale would + // read it back, but under a *different* locale (the game changed it, or the file was + // written on another machine) would not. Normalising to '.' makes the file + // locale-independent, which is what a persisted format has to be. + std::string text(buffer); + const char* decimal_point = std::localeconv()->decimal_point; + if (decimal_point != nullptr && *decimal_point != '\0' && std::string(decimal_point) != ".") { + const std::size_t at = text.find(decimal_point); + if (at != std::string::npos) { + text.replace(at, std::string(decimal_point).size(), "."); + } + } + return text; } } // namespace diff --git a/tests/test_state_writer.cpp b/tests/test_state_writer.cpp index c4d8ecc..7fa5301 100644 --- a/tests/test_state_writer.cpp +++ b/tests/test_state_writer.cpp @@ -1,4 +1,4 @@ -// The StateWriter seam (T12a). +// The IStateWriter seam (T12a). // // The verification the task asks for: each typed accessor round-trips its type; the null // writer persists nothing and the client still works; a `uint64` above `INT64_MAX` @@ -11,6 +11,7 @@ #include "test_harness.h" +#include #include #include #include @@ -21,7 +22,7 @@ using lootlocker::Client; using lootlocker::Config; using lootlocker::FileStateWriter; using lootlocker::NullStateWriter; -using lootlocker::StateWriter; +using lootlocker::IStateWriter; // A scratch file that removes itself, so a failing test does not leave state behind for the // next run to trip over. @@ -270,6 +271,67 @@ void TestClientHasADefaultWriter() CHECK(!client.GetStateWriter().expired()); } +// The default is constructed lazily, so a client that never persists anything performs no +// file I/O. That is what keeps the "no implicit config" non-negotiable true (D9): the SDK +// must not read a file on its own. +// +// The discriminator is *when* the read happens. `FileStateWriter` reads its file in its +// constructor, so the probe is deleted between constructing the client and first asking for +// the writer: a lazy default then finds nothing to load, an eager one has already loaded it. +void TestDefaultWriterIsLazy() +{ + const std::string probe = "lootlocker-state.txt"; + std::remove(probe.c_str()); + + { + std::FILE* f = std::fopen(probe.c_str(), "wb"); + CHECK(f != nullptr); + if (f != nullptr) { + std::fputs("s:probe=loaded\n", f); + std::fclose(f); + } + } + + Client client(MakeConfig()); + + // Remove the file before the writer is ever asked for. An eager default has already read + // it; a lazy one has not. + std::remove(probe.c_str()); + + std::shared_ptr writer = client.GetStateWriter().lock(); + CHECK(writer != nullptr); + if (writer != nullptr) { + std::string out; + CHECK(!writer->GetString("probe", out)); + } + + std::remove(probe.c_str()); +} + +// An injected writer means the default is never constructed at all, so no file is touched +// even when the writer is used. +void TestInjectedWriterMeansNoFileIo() +{ + const std::string probe = "lootlocker-state.txt"; + std::remove(probe.c_str()); + + std::shared_ptr writer = std::make_shared(); + + Config config = MakeConfig(); + config.state_writer = writer; + + Client client(config); + client.GetStateWriter().lock()->SetString("k", "v"); + + std::FILE* f = std::fopen(probe.c_str(), "rb"); + CHECK(f == nullptr); + if (f != nullptr) { + std::fclose(f); + } + + std::remove(probe.c_str()); +} + // An injected writer is the one used. void TestClientUsesInjectedWriter() { @@ -280,7 +342,7 @@ void TestClientUsesInjectedWriter() Client client(config); - std::shared_ptr in_use = client.GetStateWriter().lock(); + std::shared_ptr in_use = client.GetStateWriter().lock(); CHECK(in_use != nullptr); CHECK(in_use.get() == writer.get()); } @@ -316,7 +378,7 @@ void TestSetStateWriterAtRuntime() std::shared_ptr replacement = std::make_shared(); client.SetStateWriter(replacement); - std::shared_ptr in_use = client.GetStateWriter().lock(); + std::shared_ptr in_use = client.GetStateWriter().lock(); CHECK(in_use != nullptr); CHECK(in_use.get() == replacement.get()); } @@ -328,7 +390,7 @@ void TestSetStateWriterFallsBackWhenEmpty() { Client client(MakeConfig()); - client.SetStateWriter(std::weak_ptr()); + client.SetStateWriter(std::weak_ptr()); CHECK(!client.GetStateWriter().expired()); { @@ -339,6 +401,36 @@ void TestSetStateWriterFallsBackWhenEmpty() CHECK(!client.GetStateWriter().expired()); } +// A double must round-trip even when the process locale uses a decimal comma. The file is a +// persisted format, so it has to be locale-independent: a file written under one locale must +// read back under another. +void TestDoubleIsLocaleIndependent() +{ + const char* previous = std::setlocale(LC_NUMERIC, nullptr); + const std::string saved = previous == nullptr ? std::string("C") : std::string(previous); + + std::setlocale(LC_NUMERIC, "de_DE.UTF-8"); + std::setlocale(LC_NUMERIC, "German_Germany.1252"); + + TempFile file("locale"); + { + FileStateWriter writer(file.path); + writer.SetDouble("ratio", 0.1); + } + + // Read back under the C locale, which is the "written on another machine" case. + std::setlocale(LC_NUMERIC, "C"); + + FileStateWriter reopened(file.path); + double out = 0.0; + const bool ok = reopened.GetDouble("ratio", out); + + std::setlocale(LC_NUMERIC, saved.c_str()); + + CHECK(ok); + CHECK(out == 0.1); +} + } // namespace int main() @@ -356,9 +448,12 @@ int main() TestNewlineInValueIsSanitised(); TestNullWriterPersistsNothing(); TestClientHasADefaultWriter(); + TestDefaultWriterIsLazy(); + TestInjectedWriterMeansNoFileIo(); TestClientUsesInjectedWriter(); TestClientWorksWithNullWriter(); TestSetStateWriterAtRuntime(); TestSetStateWriterFallsBackWhenEmpty(); + TestDoubleIsLocaleIndependent(); return testing::Report(); }