Snapshot and Restore for an In-Memory String Map
Data Structure DesignModel answerLast updated
Build an in-memory string map in C++ that can dump its full state to a byte buffer and rebuild it, handling arbitrary bytes, corrupt input, and failed restores safely.
Design and implement, in C++, a small in-memory map from string keys to string values that can be saved to a byte buffer and restored from one.
Required operations
put(key, value): insert or replace the value forkey.get(key): return the value as anoptional<string>, ornulloptif the key is absent.erase(key): remove the key. Erasing a missing key does nothing.serialize(): return avector<uint8_t>that captures the entire current contents.deserialize(const vector<uint8_t>&): replace the contents of the store with the state described by the buffer, so that the restored store is indistinguishable from the one that was saved.
Constraints
- Use only the byte I/O helpers you are given (read/write of fixed-width integers and raw byte runs). No external serialization libraries.
- The format must be binary, versioned and length-prefixed. Keys and values may contain any bytes (including
\0, newlines and arbitrary UTF-8). - Behave correctly for an empty store, very large keys or values, repeated overwrites and deletions.
- Malformed, truncated or hostile input must be detected and reported with a clear error, not crash or allocate unbounded memory.
- Time and space for
serializeanddeserializeshould be O(n) in the total serialized size, and the encoding should work with a forward-only (streaming) reader and writer.
What to deliver
- The class and the byte layout you chose.
- Unit tests covering the edge cases above.
- A discussion of complexity, why you prefer length prefixes over delimiter-based text, and what happens to the store when a restore fails.
Hints
Hint 1
The map itself is easy (a hash map). Spend your effort on the byte layout: what must a reader know before it can safely consume each field?
Hint 2
Prefix every key and value with a fixed-width length instead of using a separator. Then no content can be mistaken for structure, and no escaping is needed. Add a magic number and a version field at the front.
Hint 3
On restore, never trust a number from the stream. Check that each requested length fits in the remaining bytes before reading or allocating, and parse into a temporary map that you swap in only after everything validated.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The data structure is just std::unordered_map<std::string, std::string>. std::string holds arbitrary bytes, so Unicode and embedded NULs are not a problem as long as the format never interprets contents. The interesting parts are the wire format and defensive parsing.
Binary format
All integers are fixed-width little-endian, written byte by byte (not by casting a struct), so the format does not depend on host endianness or padding.
magic 4 bytes "KVS\0"
version u16 1
count u64 number of entries
entries count x [ klen:u64 | key bytes | vlen:u64 | value bytes ]
- Magic rejects foreign or random data at once.
- Version allows later layouts (checksum, compression) without ambiguity.
- Length prefixes make every field self-delimiting. Embedded delimiters, NULs and any UTF-8 round-trip untouched.
- u64 lengths avoid an artificial size cap. An empty store is only the 14-byte header with
count = 0.
Why length-prefixed beats delimiter-escaped text
| Aspect | Length-prefixed binary | Delimited text with escaping |
|---|---|---|
| Arbitrary bytes | Native | Needs escape rules, easy to get wrong |
| Parse cost | One bounded read per field | Scan every byte for delimiters |
| Size | Fixed overhead (16 B/entry) | Escaping can inflate data |
| Human readable | No | Yes |
| Hostile input | Easy to bound | Ambiguity bugs are common |
Text wins only for debuggability. For a store that must carry arbitrary data, binary is the safer choice.
Serialization
Iterate the map once and append each field. Overwrites and erases are already applied to the map, so the output reflects exactly the current state. Reserve capacity up front by summing sizes to avoid reallocations.
Deserialization
- Read and check magic, then version.
- Read
count. Since every entry needs at least 16 bytes, reject ifcount > remaining / 16. This happens before any allocation, so a forged header cannot trigger a huge reserve. - For each entry, read
klen, checkklen <= remaining, read the key, and do the same for the value. Always compare againstremainingrather than computingpos + len, which can overflow. - Reject duplicate keys (a correct writer never emits them).
- After the last entry, reject trailing bytes.
- Only now
swapthe temporary map into the store.
Because parsing targets a temporary, any failure leaves the original store untouched (strong exception guarantee). Signal errors with an exception type such as DeserializeError, or a Status/expected return if exceptions are disallowed. Include the byte offset and reason in the message.
Complexity
serialize: O(N) time and space, N being total serialized size.deserialize: O(N) time, as each byte is touched a constant number of times and hash inserts are expected O(1). O(N) extra space for the temporary map.put/get/erase: expected O(|key| + |value|).
Streaming: the reader only moves forward and the writer only appends, so this maps onto ostream/istream without buffering the whole input. The one up-front field is count. For a producer that does not know the total, replace it with a per-record tag (1 = entry, 0 = end). Cost is unchanged.
Failure recovery
- Truncation at any offset, bad magic, unknown version, oversized count or length, duplicates and trailing bytes all raise an error and leave the live store as it was.
- For durability beyond the process, add a CRC32 or hash of the payload in a later version, and write snapshots to a temp file followed by an atomic rename.
Code sketch (C++)
struct DeserializeError : std::runtime_error { using std::runtime_error::runtime_error; };
class KVStore {
std::unordered_map<std::string, std::string> m_;
public:
void put(std::string k, std::string v) { m_[std::move(k)] = std::move(v); }
std::optional<std::string> get(const std::string& k) const {
auto it = m_.find(k);
if (it == m_.end()) return std::nullopt;
return it->second;
}
void erase(const std::string& k) { m_.erase(k); }
std::vector<uint8_t> serialize() const {
std::vector<uint8_t> out;
out.insert(out.end(), {'K','V','S',0});
putU16(out, 1);
putU64(out, m_.size());
for (auto& [k, v] : m_) {
putU64(out, k.size()); out.insert(out.end(), k.begin(), k.end());
putU64(out, v.size()); out.insert(out.end(), v.begin(), v.end());
}
return out;
}
void deserialize(const std::vector<uint8_t>& buf) {
Reader r(buf); // forward-only cursor
if (r.bytes(4) != "KVS\0"s) throw DeserializeError("bad magic");
if (r.u16() != 1) throw DeserializeError("unsupported version");
uint64_t count = r.u64();
if (count > r.remaining() / 16) throw DeserializeError("count too large");
std::unordered_map<std::string, std::string> tmp;
for (uint64_t i = 0; i < count; ++i) {
std::string k = r.bytes(r.u64()); // bytes() checks n <= remaining()
std::string v = r.bytes(r.u64());
if (!tmp.emplace(std::move(k), std::move(v)).second)
throw DeserializeError("duplicate key");
}
if (r.remaining()) throw DeserializeError("trailing bytes");
m_.swap(tmp); // commit only on success
}
};
Tests to include
- Empty store round-trip, empty key, empty value.
- Keys and values with
\0,\n, delimiters and multi-byte UTF-8. - Overwrite then erase, erase of a missing key, then round-trip.
- Multi-megabyte value.
- Truncation at every offset from 0 to size-1: must throw and leave the store unchanged.
- Corrupt magic, unknown version, forged huge
count, forged hugeklen, duplicate keys, trailing bytes. - Deserializing into a non-empty store replaces its contents completely.
Common mistakes
- Using
pos + len > sizeand overflowing on a hostilelen. - Calling
reserve(count)orresize(len)before validating. - Writing integers by
memcpyof a struct, which bakes in endianness and padding. - Mutating the live map during parsing, so a failure leaves a half-restored store.
- Forgetting that iteration order of an unordered map is unspecified, so tests should compare logical contents, not raw bytes. If you need deterministic output, sort keys before writing.