Skip to content

Case study: In-memory file system

Difficulty: Intermediate

Key concepts

  • tree of unique_ptr
  • non-owning parent pointer
  • std::variant node
  • Composite or variant
  • path resolution
  • validate before changing
  • map node handles
  • Result type
  • cached directory sizes
  • quotas
  • search with an explicit stack
  • How to hold files and directories as one node type with a std::variant, why that fits this problem better than the Composite pattern, and when Composite would be the better choice.
  • How a tree owns its nodes: each directory holds its children in a sorted std::map of std::unique_ptr, and each node points back to its parent with a plain pointer that owns nothing.
  • How a path such as /docs//notes/./2026/../../plan.txt is resolved one part at a time, why .. must be resolved by walking the tree and not by cutting text, and why .. at the root is refused.
  • How every operation checks everything before it changes anything, so that a refusal leaves the tree exactly as it was.
  • How mv moves a whole directory without copying it, with a commit step that allocates nothing, using a map’s node handle, and how it refuses to put a directory inside itself.
  • How a change (sizes, quotas, and search by name) lands: a cached total in every directory, a quota check on the way up to the root, and a search that is a plain loop rather than a Visitor.

This page follows the five steps of the delivery framework from How to approach a case study, the same way as Connect Four. It assumes Composite, and it uses Smart pointers and Errors and contracts throughout.

“We need a small file system that lives in memory, for a sandbox where people try out shell commands without touching a real disk. It should have directories and files, and the usual commands: make a directory, list it, write a file, read it, move or rename things, and delete them. Paths should work the way people expect.”

“The way people expect” hides most of the work. What does .. mean at the top? What happens to mv when the destination exists? What does a half-finished command leave behind? Each of those is a question to ask before any class is drawn.

The first step turns the request into a numbered list that the rest of the design can point to, and says what is left out.

Each question is here because its answer changes the design.

Question Answer (from the team) What it changes
Is there a current directory, so that docs/a.txt means something? No. Every command gets a full path from /. The sandbox’s shell keeps its own current directory. Only absolute paths. A path without a leading / is refused.
Are . and .. allowed in paths? Yes, anywhere in the path. The path must be resolved against the tree, part by part.
What does /.. mean? Some shells quietly treat it as /. We would rather tell the user. .. at the root is refused with invalid_path.
Are // and a trailing / errors? No, ignore them. Empty parts between slashes are skipped.
What kinds of thing are there? Files and directories. No links, devices, or special files. Two kinds, and they are not expected to grow (this matters for Composite or variant).
What is in a file? Bytes. The tests use text. A std::string of bytes. No encodings.
What does mv do when the destination exists? Refuse. People lose work when a move quietly replaces a file. mv never replaces anything, file or directory.
Can a directory be moved into itself? It must be refused. mv checks that the new parent is not the directory or below it.
May rm remove a directory that has things in it? Only when asked to, like rm -r. A Recursive flag.
Should mkdir create missing parents? Only when asked to, like mkdir -p. A Parents flag.
What should a refused command say? A kind of error the shell can react to, and a sentence the user can read. Every refusal is an Error code and a reason.
What if a command fails half way? It must not. A command does all of its work or none of it. Every operation checks first and changes last.
One user at a time? Yes. One sandbox, one thread. No locks. The documentation says it is not thread-safe.
Does it need to survive a restart? No. The sandbox starts empty each time. No persistence.

Three answers decide the shape. “Paths with . and ..” means the path has to be read against the tree, not as text. “mv must refuse when the destination exists, and never move a directory into itself” means mv does most of its work in checks. And “all of its work or none of it” puts every check before the first change, in every operation.

Confirmed:

  • One tree under /, of directories and files.
  • Absolute paths with ., .., repeated slashes, and a trailing slash.
  • mkdir (with and without parents), ls, write (overwrite and append), read, mv (rename and move), and rm (empty only, or recursive).
  • A code and a reason for every refusal, and no change when a command refuses.

Assumed (to confirm with the team; see Assumptions):

  • ls sorts names in byte order, so B comes before a and 10 before 9. A shell that sorts for people would choose differently.
  • A name may hold any byte except / and the zero byte, and may not be empty, ., or ... There is no length limit.
  • ls of a file lists the file itself, as a shell does.

Out of scope: a current directory and relative paths, permissions and owners, links, times, more than one thread, persistence, and the shell that parses command lines. Sizes, quotas, and search by name arrive as a change, in Step 5 of the framework: Extensibility.

Functional requirements.

  • FR-1 Paths. Every path is absolute. . stays, .. goes to the parent, and repeated or trailing slashes are ignored. .. at the root is refused, and a file has nothing below it, not even . or ...
  • FR-2 mkdir. Creates an empty directory whose parent exists and whose name is free. With parents, it creates every missing directory on the way and accepts a directory that already exists.
  • FR-3 ls. Lists a directory’s children sorted by name, marking which are directories, or lists a file by itself.
  • FR-4 write and read. write creates a file, replaces its bytes, or appends to them; its parent must exist. read returns a file’s bytes.
  • FR-5 mv. Renames or moves a file or a directory with everything below it. It never replaces an existing entry, and never moves a directory into itself or below itself. The root cannot be moved.
  • FR-6 rm. Removes a file or an empty directory, or, when asked, a directory with everything below it. The root cannot be removed.
  • FR-7 Refusals. Every refusal has an error code and a reason in words, and a refused command changes nothing.

Non-functional requirements.

  • NFR-1 Clear ownership. Every node is owned by exactly one directory (the root by the file system). Nothing leaks, and there are no cycles of owners.
  • NFR-2 All or nothing. No command leaves a partial change, even if memory runs out part way.
  • NFR-3 A fixed order. ls (and, in step 2, search) give the same order every time.
  • NFR-4 Not thread-safe, on purpose. One thread uses the file system at a time, and the documentation says so.
  • NFR-5 Testable on its own. The tree can be checked as a whole (consistent), and a path’s resolution can be seen step by step (trace).

FR-7 and NFR-2 together are the rule that shapes every function on this page: check everything, then change.

The tests are named after these criteria (ac_1_1_… is AC-1.1). See Use cases, user stories, and acceptance criteria. The tests start from a small tree: /docs/a.txt holding alpha, /docs/notes/b.txt holding beta, and an empty /tmp.

UC-1 Resolve a path.

  • AC-1.1 A path that is empty, does not start with /, or holds a zero byte is refused (invalid_path).
  • AC-1.2 Repeated and trailing slashes are ignored: //docs///a.txt reads alpha.
  • AC-1.3 . stays and .. goes to the parent: /docs/./notes/../a.txt reads alpha, and ls /docs/.. lists docs/ tmp/.
  • AC-1.4 .. above the root is refused (invalid_path), as in /.. and /docs/../../docs/a.txt.
  • AC-1.5 A file has no parts below it: /docs/a.txt/x, /docs/a.txt/.., and /docs/a.txt/. are refused (not_a_directory). A missing name is reported first: /docs/missing/.. is not_found.
  • AC-1.6 A name is not empty, not . or .., and holds neither / nor a zero byte. ... is a valid name.
  • AC-1.7 A change must name its entry with a real name: mkdir /docs/.., write /docs/notes/.., rm /docs/notes/.., and mv from or to a path ending in . are refused, and the tree does not change.
  • AC-1.8 trace shows each part read and where it led, or the reason it stopped.

UC-2 Make a directory.

  • AC-2.1 mkdir /docs creates an empty directory.
  • AC-2.2 A name that is taken, by a directory or a file, is refused (already_exists), and so is mkdir /.
  • AC-2.3 Without parents, a missing parent is refused (not_found, “‘x’ does not exist in /”), and a file as the parent is not_a_directory.
  • AC-2.4 With parents, every missing directory is created, and .. works through the new ones.
  • AC-2.5 With parents, a directory that exists is fine (even /), and a file that exists is already_exists.
  • AC-2.6 With parents, a refusal changes nothing, including when the missing part of the path holds . or ...

UC-3 List.

  • AC-3.1 ls is sorted by name in byte order: 10 9 B a a-c b c/.
  • AC-3.2 ls of a file lists that file; ls of an empty directory lists nothing.
  • AC-3.3 ls of a missing path is refused with a reason that names the missing part and where it was looked for.

UC-4 Write and read.

  • AC-4.1 write creates a file, and read returns its bytes, also for an empty file.
  • AC-4.2 write replaces the bytes, and append adds to them.
  • AC-4.3 Append to a missing file creates it.
  • AC-4.4 write to a directory (or /) is is_a_directory; a missing parent is not_found; a file as the parent is not_a_directory. Nothing changes.
  • AC-4.5 read of a directory is is_a_directory; of a missing file, not_found.

UC-5 Move or rename.

  • AC-5.1 mv renames a file or a directory in place.
  • AC-5.2 mv moves a directory with everything below it, and .. from it now leads to its new parent.
  • AC-5.3 mv moves up and across the tree.
  • AC-5.4 A directory into itself or below it is refused (into_itself), however the path is written, and nothing changes.
  • AC-5.5 mv never replaces: a file, a directory, the source itself, or / as the destination is already_exists.
  • AC-5.6 A missing source or destination directory, a file as the destination’s parent, the root as the source, and relative paths are refused, and nothing changes.

UC-6 Remove.

  • AC-6.1 rm removes a file and an empty directory; the recursive flag is fine on a file.
  • AC-6.2 A directory that is not empty is refused (not_empty) without the flag.
  • AC-6.3 With the flag, everything below goes too.
  • AC-6.4 The root (/ or //) is is_root; a missing entry is not_found.

UC-7 The whole tree.

  • AC-7.1 Every refusal has a code other than none and a reason that is not empty; a command that worked has none and no reason.
  • AC-7.2 After a mixed run of mkdir, write, mv, and rm, the tree is consistent and holds exactly what it should.

Each invariant names the code that keeps it. See Invariants.

  • INV-1 A tree of owners. Every node except the root is owned by exactly one std::unique_ptr, in its parent directory’s map. The root is a member of FileSystem. Kept by the types: a unique_ptr cannot be copied, so a node cannot end up in two maps.
  • INV-2 Parent pointers are right. Every child’s parent points at the directory whose map holds it, and only the root’s is nullptr. Kept by mkdir and write, which build each node with its parent, and by mv, which sets it. Checked by consistent.
  • INV-3 Names are valid, and stored once. Every key in every map is a valid name, and a node does not store its own name. Kept by target and mkdir, which check with is_valid_name.
  • INV-4 No directory is inside itself. Kept by the climb in mv.
  • INV-5 A refusal changes nothing. Kept by the order inside each operation: every check, then the change. Tested by comparing a snapshot of the whole tree before and after each refusal.

Step 2 of the framework: Entities and relationships

Section titled “Step 2 of the framework: Entities and relationships”

The nouns from the answers: file system, path, root, directory, file, name, bytes, parent, child, command, refusal, reason. Filtered:

  • File system is the FileSystem class: it owns the root and offers the commands.
  • Directory and file are the two kinds of node. Both have a parent and live in a directory under a name, so they share one Node type, and what differs (children or bytes) is a std::variant<File, Directory>.
  • Name is the key under which a directory holds a child. It is not stored in the node, so a rename changes one string in one place.
  • Path is a string that is split into names and walked; it is not stored anywhere. Root is the one node with no parent.
  • Bytes are a std::string in a File.
  • Command is a member function of FileSystem. Refusal and reason are a Failure (an Error code and a sentence) inside a Result.
Entity sketch for step 1. Solid arrow: owns. Dashed arrow: knows without owning
Text description of the diagram

There are five boxes. FileSystem owns one Node, the root. A Node owns exactly one of a File or a Directory. A File owns its bytes, a std::string. A Directory owns zero or more Nodes, each under a name. A Node knows zero or one other Node, its parent, without owning it: the root has no parent, and every other node’s parent is the directory that owns it.

Diagram source (Mermaid)
flowchart TD
FS["FileSystem"] -->|"owns 1 (the root)"| N["Node"]
N -->|"owns 1 of"| F["File"]
N -->|"owns 1 of"| D["Directory"]
F -->|"owns 1"| B["bytes (std::string)"]
D -->|"owns 0..* by name"| N
N -.->|"knows 0..1 (its parent)"| N

Read the arrows as the rules of ownership. Every solid arrow points down the tree, so destroying a directory destroys everything below it. The only arrow that points up is dashed: a node knows its parent but does not keep it alive. That one choice is what makes the tree free of ownership cycles (NFR-1), and the first flawed design below shows what happens without it.

The design below is step 1 of the example, the complete answer to FR-1 … FR-7. Sizes, quotas, and search are added in Step 5.

Requirement Class What it must remember
FR-1 .. goes to the parent Node Node* parent, the directory above it (nullptr for the root)
FR-2, FR-3 directories and their names Directory Children children, a std::map from name to std::unique_ptr<Node>, sorted by name
FR-4 files hold bytes File std::string data
a node is a file or a directory Node std::variant<File, Directory> content
one tree under / FileSystem Node root_, a member
FR-7 a code and a reason Failure Error error, std::string reason

Notice what is not remembered. A node has no name field and no path field: its name is the key in its parent’s map, and its path is found by climbing parent pointers. Each fact is stored once, so a rename or a move cannot leave two copies that disagree.

Need Member function
make a directory, with or without parents Status FileSystem::mkdir(std::string_view, Parents)
list a directory Result<std::vector<Entry>> FileSystem::ls(std::string_view) const
write or append bytes Status FileSystem::write(std::string_view, std::string_view, WriteMode)
read bytes Result<std::string> FileSystem::read(std::string_view) const
rename or move Status FileSystem::mv(std::string_view, std::string_view)
remove Status FileSystem::rm(std::string_view, Recursive)
see how a path resolves (NFR-5) std::vector<Step> FileSystem::trace(std::string_view) const
check the whole tree (NFR-5) bool FileSystem::consistent() const
shared by all: follow a path through the tree private walk
shared by changes: the parent and the new name private target
say whether it worked, and why not Result<T>::ok, error, reason, value

Every command takes a std::string_view, so a caller can pass a string literal or a std::string without a copy, and gives back a Result. None of them throws for a refusal: a missing file is an ordinary answer in a file system, not an exceptional one. (An out-of-memory std::bad_alloc can still be thrown, and the design makes sure it leaves the tree unchanged.)

struct Node

one type for files and directories

Data members

  • Node* parent = nullptr; public; non-owning; nullptr only for the root
  • std::variant<File, Directory> content; public

struct File

Data members

  • std::string data; public; the bytes

struct Directory

Data members

  • Children children; public; std::map<std::string, std::unique_ptr<Node>, std::less<>>

class FileSystem

cannot be copied or moved

Data members

  • Node root_; a member: its children point back at it

Member functions

  • Status mkdir(std::string_view path, Parents parents = Parents::must_exist);
  • Result<std::vector<Entry>> ls(std::string_view path) const;
  • Status write(std::string_view path, std::string_view data, WriteMode mode = WriteMode::overwrite);
  • Result<std::string> read(std::string_view path) const;
  • Status mv(std::string_view from, std::string_view to);
  • Status rm(std::string_view path, Recursive recursive = Recursive::no);
  • std::vector<Step> trace(std::string_view path) const;
  • bool consistent() const; for tests
  • Result<Reached> walk(const std::vector<std::string>& parts, OnMissing missing, std::vector<Step>* trace) const; private
  • Result<Target> target(std::vector<std::string> parts); private

class Result<T>

a value or the reason there is none

Data members

  • std::variant<T, Failure> outcome_;

Member functions

  • bool ok() const noexcept;
  • Error error() const noexcept; Error::none when it worked
  • std::string reason() const; empty when it worked
  • const T& value() const&;
  • T value() &&; a temporary hands its value over

struct Failure

Data members

  • Error error; public
  • std::string reason; public

enum class Error

Values

  • none
  • invalid_path
  • not_found
  • not_a_directory
  • is_a_directory
  • already_exists
  • not_empty
  • into_itself
  • is_root
Class outlines for step 1. A minus sign marks a data member and a plus sign a member function; data members are private unless the outline says public

Status is Result<Done>, for commands that have nothing to return but success. Entry (a name and a Kind) is one line of ls, and Step (a part and where it led) is one line of trace.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

node.hpp
// One node type for both files and directories. A Node holds a
// std::variant: either File content or Directory children.
//
// Why a variant here, and not Composite (a Node base class with File and
// Directory classes derived from it)?
// - The kinds of node are fixed: a file or a directory. The operations
// keep growing (mkdir, ls, write, read, mv, rm, and in step 2 sizes and
// search). With a variant, a new operation is one more function that
// looks at the alternatives; with Composite it is often one more
// virtual function in every class, or a dynamic_cast.
// - Most operations treat files and directories differently (read wants
// a file, ls and mkdir want a directory), so there is little shared
// behaviour for a base class to hold.
// - Moving a node between directories never changes its kind, so the
// variant never needs to switch alternative.
// When Composite fits better: when new kinds keep arriving (links, devices,
// mount points) and each kind answers the same few questions (its size,
// how to print it) in its own way. Then a virtual function per question
// keeps each kind's code together, and adding a kind does not touch the
// existing ones.
struct Node;
// The children of a directory, by name. std::map keeps the names sorted,
// so ls is in a fixed order for free. std::less<> lets find() take a
// std::string_view without first building a std::string.
// Each child is owned by a std::unique_ptr: the directory owns its
// children, so destroying a directory destroys everything below it, and
// nothing else may delete a node. Every node but the root is on the heap,
// so its address never changes while it exists, even when mv hands it to
// another directory; the parent pointers in its children stay valid.
using Children = std::map<std::string, std::unique_ptr<Node>, std::less<>>;
struct File {
std::string data; // the bytes of the file; text in the examples
};
struct Directory {
Children children;
};
struct Node {
// The directory that owns this node. Non-owning: it only points back
// up. nullptr only for the root, which has no parent, so ".." at the
// root is refused. mv must set it when the node changes directory.
Node* parent = nullptr;
std::variant<File, Directory> content;
};
// A node does not store its own name: the key in its parent's map is the
// only copy, so a rename cannot leave two names that disagree.
//
// Limit: destroying a node destroys its children first, through the
// unique_ptr destructors, so tearing down a tree recurses once per level.
// The trees in these examples are a few levels deep; a tree thousands of
// levels deep could overflow the stack, and a real system would limit the
// depth or take the tree apart with a loop.

Three decisions sit in this short header.

One node type with a variant, not a class hierarchy. The comment gives the reasons; here they are side by side with the alternative.

Question One Node holding std::variant<File, Directory> Composite: a Node base with File and Directory derived
Add an operation (sizes, search) One more function that looks at the alternatives Often one more virtual function in every class
Add a kind of node (links, devices) Every function that looks at the alternatives must change One more derived class; existing classes stay as they are
Ask “is this a directory?” std::get_if<Directory>, checked, no cast A virtual query or a dynamic_cast
Behaviour shared by both kinds Little here: most commands want one kind or the other Shines when every kind answers the same few questions
Where a node’s parent lives Once, in Node Once, in the base class
Memory One allocation per node, sized for the larger alternative One allocation per node, sized for its own class

This problem has a fixed, short list of kinds and a growing list of operations, which is the case a variant handles well. The team said “no links, devices, or special files”. If that answer were “yes, and more later”, each new kind would touch every function that switches on the variant, and Composite, with each kind’s behaviour kept in its own class, would be the better fit. The Composite page builds exactly that version, and also shows a value tree with std::variant, so the two can be compared.

Children in a sorted std::map of std::unique_ptr. The map keeps names sorted, so ls is in a fixed order (NFR-3) with no sorting step. The unique_ptr makes the directory the one owner of each child (INV-1). And because each child lives on the heap, its address does not change when the map rebalances, or when mv hands it to another map, so the parent pointers held by its children stay valid.

A plain Node* back to the parent. It is non-owning: a child never keeps its parent alive. It is nullptr only for the root, which is how walk knows that .. at the root has nowhere to go. A raw pointer is right here because the parent always outlives the child (it owns it); the cost is that every operation that moves a node must set it, and only mv does.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

result.hpp
// Why an operation was refused. Every refusal carries one of these codes,
// so a test (or a shell) can react to the kind of problem, and a sentence
// in plain words for a person to read.
enum class Error {
none, // not a refusal: reported only by a Result that worked
invalid_path, // not an absolute path, a bad name, or ".." above the root
not_found, // a name on the path does not exist
not_a_directory, // a file was found where a directory was needed
is_a_directory, // a directory was found where a file was needed
already_exists, // the new name is taken (mv never replaces anything)
not_empty, // rm of a directory that still has children, without the recursive flag
into_itself, // mv of a directory into itself or into one of its own descendants
is_root, // the root cannot be removed or moved
};

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

result.hpp
// What an operation gives back: either the value it produced, or the
// Failure that says why it refused. C++23 has std::expected for this; the
// examples use C++20, so this is a small stand-in built on std::variant.
// The two constructors are deliberately not explicit, so a function can
// write `return Failure{...};` or `return value;` and both become a Result.
// [[nodiscard]] makes the compiler warn when a caller ignores a Result,
// which is how refusals usually get lost.
template <typename T>
class [[nodiscard]] Result {
public:
Result(T value) : outcome_(std::move(value)) {}
Result(Failure failure) : outcome_(std::move(failure)) {}
[[nodiscard]] bool ok() const noexcept { return std::holds_alternative<T>(outcome_); }
// Error::none when the operation worked, so tests can compare codes
// without checking ok() first.
[[nodiscard]] Error error() const noexcept {
// std::get_if gives a pointer to the Failure, or nullptr when the
// variant holds a value instead.
const Failure* failure = std::get_if<Failure>(&outcome_);
return failure != nullptr ? failure->error : Error::none;
}
// A copy, "" when the operation worked. A copy (not a std::string_view)
// so that `fs.rm(p).reason()` stays valid after the Result is gone.
[[nodiscard]] std::string reason() const {
const Failure* failure = std::get_if<Failure>(&outcome_);
return failure != nullptr ? failure->reason : std::string{};
}
// Only call these after checking ok() (value) or !ok() (failure):
// std::get throws std::bad_variant_access if the other one is held.
// The & and && after the parentheses choose by what the Result is: a
// named Result (&) lends a reference to its value; a temporary one
// (&&), as in `fs.read(p).value()`, moves the value out, so the caller
// never holds a reference into a Result that has been destroyed.
[[nodiscard]] const T& value() const& { return std::get<T>(outcome_); }
[[nodiscard]] T& value() & { return std::get<T>(outcome_); }
[[nodiscard]] T value() && { return std::get<T>(std::move(outcome_)); }
[[nodiscard]] const Failure& failure() const { return std::get<Failure>(outcome_); }
private:
std::variant<T, Failure> outcome_;
};
How this code works: Result and its three value() overloads
  1. One of two things. A Result<std::string> holds a std::variant<std::string, Failure>: either the bytes that read found, or the reason it did not. ok() asks which one is there.
  2. Two ways to read a refusal. error() gives the code (a test or a shell can switch on it), and reason() the sentence for a person. Both are safe to call on a success: they give Error::none and an empty string.
  3. Why value() has three versions. The &, const&, and && after the parentheses choose a version by what the Result is. For a named Result, the first two lend a reference to the value inside. For a temporary, such as the one fs.read("/a.txt") returns when it is used straight away, && is chosen, and it moves the value out and returns it by value.
  4. What that prevents. Without the && version, const std::string& text = fs.read("/a.txt").value(); would bind text to a string inside a temporary that is destroyed at the end of the line, leaving a dangling reference. With it, value() returns a std::string by value, and binding a const& to that returned temporary extends its life to match text. The same idea is why reason() returns a copy.
  5. [[nodiscard]] on the class. Every function that returns a Result is then [[nodiscard]] by itself: writing fs.rm("/x"); and ignoring the answer makes the compiler warn, which is how refusals usually get lost.

C++23 adds std::expected, which does the same job; the examples on this site use C++20, so this small stand-in is built on std::variant. See Errors and contracts for when to return an error and when to throw.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file_system.hpp
// An in-memory file system: a tree of directories and files under one
// root. Every operation takes an absolute path (see split_path).
//
// Every operation either does all of its work or none of it. Each one
// first checks everything that could make it refuse, and changes nothing
// until all checks have passed. Anything that allocates memory (a new
// node, a new name) is built before the first change, so running out of
// memory leaves the tree as it was. The change itself is then a step that
// cannot fail, or one standard-library call that either happens in full
// or not at all.
//
// The FileSystem cannot be copied or moved. Its root is a member, and
// every child of the root points back at that member; moving the
// FileSystem would move the root and leave those pointers dangling.
class FileSystem {
public:
FileSystem() = default;
FileSystem(const FileSystem&) = delete;
FileSystem& operator=(const FileSystem&) = delete;
// Creates a directory. With Parents::must_exist the parent must exist
// and the name must be free. With Parents::create, missing directories
// on the way are created too, and a directory that already exists is
// fine; the parts still to be created must then be plain names.
Status mkdir(std::string_view path, Parents parents = Parents::must_exist);
// A directory's children sorted by name (byte order: "B" before "a"),
// or, for a file, the file alone.
[[nodiscard]] Result<std::vector<Entry>> ls(std::string_view path) const;
// Creates the file, or replaces (overwrite) or extends (append) its
// bytes. The parent directory must already exist.
Status write(std::string_view path, std::string_view data,
WriteMode mode = WriteMode::overwrite);
[[nodiscard]] Result<std::string> read(std::string_view path) const;
// Renames or moves a file or directory. `to` is the new full path. The
// rule against overwriting: mv never replaces anything. If `to` exists
// at all, file or directory, mv refuses with already_exists; it does
// not move into an existing directory the way the shell's mv does.
Status mv(std::string_view from, std::string_view to);
// Removes a file, or a directory that is empty. With Recursive::yes a
// directory goes with everything below it.
Status rm(std::string_view path, Recursive recursive = Recursive::no);
// How `path` is resolved, one part at a time. For teaching and tests.
[[nodiscard]] std::vector<Step> trace(std::string_view path) const;
// True if every node's parent pointer names the directory that owns
// it. For tests: it should hold after every operation.
[[nodiscard]] bool consistent() const;
private:
// Where a walk ended, and how many parts it followed to get there.
struct Reached {
const Node* node;
std::size_t used;
};
enum class OnMissing { refuse, stop };
// The directory a change applies to, and the name inside it.
struct Target {
Node* parent; // always a directory
std::string name;
};
[[nodiscard]] Result<Reached> walk(const std::vector<std::string>& parts, OnMissing missing,
std::vector<Step>* trace = nullptr) const;
[[nodiscard]] Result<const Node*> locate(std::string_view path) const;
[[nodiscard]] Result<Target> target(std::vector<std::string> parts);
[[nodiscard]] Node& mutable_node(const Node& node);
Node root_{nullptr, Directory{}};
};

The class comment states the rule that every function below keeps: check, build, then change. The other note is easy to miss. The root is a member, not a heap node, so every child of the root points at memory inside the FileSystem object. Copying or moving the object would leave those pointers aimed at the old object, so both are deleted. A caller that needs a movable file system can hold it in a std::unique_ptr<FileSystem>.

Every command has the same shape, and it is worth seeing once before the details:

  1. Split the path into names (split_path). A bad path stops here.
  2. Walk the tree to the directory the command works in (walk, or target for a change). A missing or wrong node stops here.
  3. Check every other rule of the command (a name is free, a directory is empty, a directory is not moving into itself).
  4. Build anything that needs memory (a new node, a new name).
  5. Change the tree, with steps that cannot fail.

A refusal can happen in steps 1 to 4, and none of them has changed the tree. That is the whole of FR-7 and NFR-2.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

path.hpp
// Splits an absolute path into its parts, without looking at the tree.
// "/docs//notes/./a.txt/" -> {"docs", "notes", ".", "a.txt"}
// "/" -> {} (no parts: the root itself)
// Rules:
// - The path must start with '/'. There is no current directory, so a
// relative path such as "docs/a.txt" is refused (invalid_path).
// - Repeated slashes and a trailing slash are ignored: an empty part
// between two slashes is skipped, never treated as a name.
// - "." and ".." are kept. Only the walk through the tree can tell what
// ".." means, because "/docs/.." is the root only if /docs is a directory.
// - An empty path, or one holding a '\0' byte, is refused (invalid_path).
[[nodiscard]] Result<std::vector<std::string>> split_path(std::string_view path);
// True if `name` may name a file or directory: not empty, not "." or "..",
// and holding neither '/' (which separates parts) nor '\0'. A part split
// from a path never holds either, but the rule is written in full so that
// it is right wherever a name is checked (consistent() checks every name).
[[nodiscard]] bool is_valid_name(std::string_view name) noexcept;
// "/" + name below the root, otherwise parent + "/" + name.
[[nodiscard]] std::string join(std::string_view parent, std::string_view name);

split_path only cuts text. It refuses what is wrong without looking at the tree (an empty path, a relative path, a zero byte), drops the empty parts that // and a trailing / make, and keeps . and .. as parts. It cannot do more, because what .. means depends on the tree: /docs/.. is the root only if /docs exists and is a directory.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file_system.cpp
// Follows `parts` from the root, one at a time, and returns the node
// reached. The rules, in order, for each part:
// 1. The node reached so far must be a directory, even for "." and "..":
// "/a.txt/.." is refused (not_a_directory), as a shell would.
// 2. "." stays where it is.
// 3. ".." goes to the parent. At the root it is refused (invalid_path):
// the root has no parent, and "/.." is not quietly the root.
// 4. Any other part must be a child's name (not_found otherwise), unless
// `missing` is OnMissing::stop: then the walk stops there without
// refusing, and Reached::used says how many parts it followed.
// If `trace` is not null, each part read is added to it with the path
// reached, or with the reason the walk stopped.
Result<FileSystem::Reached> FileSystem::walk(const std::vector<std::string>& parts,
OnMissing missing, std::vector<Step>* trace) const {
// Records the refusal in the trace (if any) and returns it. A lambda
// that captures `trace`, a pointer, by reference; it adds to the
// caller's list through that pointer (a copy of the pointer would work too).
auto refuse = [&trace](const std::string& part, Failure failure) -> Result<Reached> {
if (trace != nullptr) trace->push_back(Step{part, "error: " + failure.reason});
return failure;
};
const Node* at = &root_;
for (std::size_t i = 0; i < parts.size(); ++i) {
const std::string& part = parts[i];
const auto* dir = std::get_if<Directory>(&at->content);
if (dir == nullptr) {
return refuse(part, Failure{Error::not_a_directory,
path_of(*at) + " is a file, so it has no " + quoted(part)});
}
if (part == ".") {
// stay at `at`
} else if (part == "..") {
if (at->parent == nullptr) {
return refuse(part,
Failure{Error::invalid_path,
"'..' at / would go above the root, which has no parent"});
}
at = at->parent;
} else {
auto child = dir->children.find(part);
if (child == dir->children.end()) {
if (missing == OnMissing::stop) return Reached{at, i};
return refuse(part, Failure{Error::not_found, quoted(part) + " does not exist in " +
path_of(*at)});
}
at = child->second.get();
}
if (trace != nullptr) trace->push_back(Step{part, path_of(*at)});
}
return Reached{at, parts.size()};
}
How this code works: FileSystem::walk on the demo's path

The step 1 demo has made /docs, /docs/notes/2026, and the file /docs/plan.txt, and then asks for the trace of /docs//notes/./2026/../../plan.txt. split_path drops the empty part between //, so walk gets seven parts. at starts at the root.

i Part at before Rule used at after
0 docs / 4: a child’s name /docs
1 notes /docs 4: a child’s name /docs/notes
2 . /docs/notes 2: stay /docs/notes
3 2026 /docs/notes 4: a child’s name /docs/notes/2026
4 .. /docs/notes/2026 3: go to parent /docs/notes
5 .. /docs/notes 3: go to parent /docs
6 plan.txt /docs 4: a child’s name /docs/plan.txt
  1. Rule 1 runs first, every time. At the top of each pass, std::get_if<Directory> checks that the node reached so far is a directory. Here every at before is one. The last node reached is a file, which is fine: rule 1 only applies when there is another part to read.
  2. . and .. are rules, not names. They are never looked up in the map, so a file called .. cannot exist (and is_valid_name refuses to make one).
  3. .. uses the parent pointer. Passes 4 and 5 follow at->parent. That pointer is why a Node has one.
  4. The trace line is added after each part, with path_of(*at), which climbs the parent pointers to spell out the path. That climb costs time, so it only happens when a trace was asked for, or when a refusal needs to name the place where it stopped.
  5. The result is Reached{node, 7}: the node, and that all seven parts were used.

The second trace in the demo, /docs/../.., goes / to /docs, then .. back to /, and then meets .. at the root: at->parent is nullptr, so refuse adds the error line to the trace and returns invalid_path.

Resolving /docs//notes/./2026/../../plan.txt, one part at a time (from the step 1 demo's output)
Text description of the diagram

The walk starts at the root. Reading docs leads to /docs, and notes to /docs/notes. The dot stays at /docs/notes. Reading 2026 leads to /docs/notes/2026. The first dot-dot follows the parent pointer back to /docs/notes, and the second to /docs. Reading plan.txt leads to the file /docs/plan.txt, where the walk ends because there are no more parts. The empty part between the two slashes after docs was dropped by split_path before the walk began.

Diagram source (Mermaid)
flowchart TD
S0["/"] -->|"docs"| S1["/docs"]
S1 -->|"notes"| S2["/docs/notes"]
S2 -->|"."| S3["/docs/notes (stays)"]
S3 -->|"2026"| S4["/docs/notes/2026"]
S4 -->|".. (parent)"| S5["/docs/notes"]
S5 -->|".. (parent)"| S6["/docs"]
S6 -->|"plan.txt"| S7["/docs/plan.txt (a file)"]

The demo prints the same steps, from fs.trace:

Path Trace printed by the step 1 demo
/docs//notes/./2026/../../plan.txt /, docs to /docs, notes to /docs/notes, . to /docs/notes, 2026 to /docs/notes/2026, .. to /docs/notes, .. to /docs, plan.txt to /docs/plan.txt
/docs/../.. /, docs to /docs, .. to /, .. to “error: ‘..’ at / would go above the root, which has no parent”

The tests add three more cases to the trace (AC-1.8): a missing name (/docs/nope/x stops at nope with “‘nope’ does not exist in /docs”), .. below a file (/docs/a.txt/.. stops with “/docs/a.txt is a file, so it has no ‘..’”), and a relative path, which stops in split_path before the walk.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file_system.cpp
// For a change: the directory that holds (or will hold) the last part of
// the path, and that last part as a name. The last part must be a real
// name, so "/docs/.." or "/docs/." cannot be created, removed, or moved.
// The name is returned as a std::string built here, before any change, so
// a later step can move it into the tree instead of copying it (in mv, the
// commit then allocates nothing at all).
Result<FileSystem::Target> FileSystem::target(std::vector<std::string> parts) {
if (parts.empty()) return Failure{Error::is_root, "this change cannot apply to /"};
std::string name = std::move(parts.back());
parts.pop_back();
if (!is_valid_name(name)) {
return Failure{Error::invalid_path,
quoted(name) + " cannot name an entry; the last part must be a real name"};
}
auto reached = walk(parts, OnMissing::refuse);
if (!reached.ok()) return reached.failure();
const Node* parent = reached.value().node;
if (!std::holds_alternative<Directory>(parent->content)) {
return Failure{Error::not_a_directory,
path_of(*parent) + " is a file, so it cannot hold " + quoted(name)};
}
return Target{&mutable_node(*parent), std::move(name)};
}

Every command that changes the tree (mkdir, write, mv, rm) needs two things: the directory that holds the entry, and the entry’s name. target cuts the last part off and walks to the rest. The last part must be a real name: mkdir /docs/.. would otherwise mean “make the root”, and rm /docs/notes/.. would mean “remove /docs”, which nobody typing it would expect (AC-1.7). Paths that only read (ls, read) may end in . or .., because they never need a name.

The name is returned as a std::string that target built, for a reason that only shows up in mv: building a string can need memory, and mv wants every allocation done before its first change.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file_system.cpp
Status FileSystem::mkdir(std::string_view path, Parents parents) {
auto parts = split_path(path);
if (!parts.ok()) return parts.failure();
if (parts.value().empty()) {
// The root always exists; mkdir -p accepts a directory that exists.
if (parents == Parents::create) return Done{};
return Failure{Error::already_exists, "/ always exists"};
}
if (parents == Parents::must_exist) {
auto place = target(std::move(parts.value()));
if (!place.ok()) return place.failure();
auto& [parent, name] = place.value();
Children& children = std::get<Directory>(parent->content).children;
if (children.contains(name)) {
return Failure{Error::already_exists, join(path_of(*parent), name) + " already exists"};
}
// Allocate the node first. emplace then either inserts it or, if it
// throws (out of memory), leaves the map unchanged and the node is
// freed with `node`.
auto node = std::make_unique<Node>(Node{parent, Directory{}});
children.emplace(std::move(name), std::move(node));
return Done{};
}
// With parents: follow the directories that exist, and stop at the first
// missing name. Everything from there on is to be created.
const std::vector<std::string>& all = parts.value();
auto reached = walk(all, OnMissing::stop);
if (!reached.ok()) return reached.failure();
const auto [found, used] = reached.value();
if (used == all.size()) {
if (std::holds_alternative<Directory>(found->content)) return Done{};
return Failure{Error::already_exists, path_of(*found) + " exists and is a file"};
}
// A directory that does not exist yet has no "." or "..", so the parts
// still to be created must all be plain names. This is checked before
// anything is built.
for (std::size_t i = used; i < all.size(); ++i) {
if (!is_valid_name(all[i])) {
return Failure{Error::invalid_path,
quoted(all[i]) + " follows a directory that does not exist yet"};
}
}
// Build first: the missing directories as a chain hanging from `top`,
// not yet in the tree. If memory runs out here, `top` frees the chain.
Node& parent = mutable_node(*found);
auto top = std::make_unique<Node>(Node{&parent, Directory{}});
Node* bottom = top.get();
for (std::size_t i = used + 1; i < all.size(); ++i) {
auto child = std::make_unique<Node>(Node{bottom, Directory{}});
Node* next = child.get(); // read before std::move empties `child`
std::get<Directory>(bottom->content).children.emplace(all[i], std::move(child));
bottom = next;
}
// Then commit: one insertion links the whole chain into the tree, or,
// if it throws, changes nothing.
std::get<Directory>(parent.content).children.emplace(all[used], std::move(top));
return Done{};
}

Without parents, mkdir is check, build, insert. With parents, the idea is the same but the build is longer.

How this code works: mkdir -p /docs/notes/2026 in the step 1 demo

The tree holds only /docs, which the demo made a line earlier.

  1. Walk as far as the tree goes. walk with OnMissing::stop finds docs, then does not find notes, and returns Reached{/docs, 1}: it stopped at /docs after using one part.

  2. Everything from used on is new. all[1] is notes and all[2] is 2026. Both must be plain names: a directory that does not exist yet has no . or .. inside it, so mkdir -p /new/./y is refused (AC-2.6), before anything is built.

  3. Build the chain off the tree. top is a new directory notes whose parent pointer already names /docs. The loop makes 2026 with bottom (notes) as its parent, and puts it in notes’s map. Nothing in the tree has changed: the chain hangs from top, a local std::unique_ptr.

    Variable Points at In the tree?
    parent /docs yes
    top the new notes not yet
    bottom the new 2026, in notes not yet
  4. Commit with one insertion. emplace("notes", std::move(top)) links the whole chain into /docs. If it throws (out of memory), the map is unchanged and top still frees the chain; if it works, the chain is in the tree. There is no moment at which /docs/notes exists without 2026.

  5. Node* next = child.get() is read before std::move(child), because after the move child is empty. The node itself has not moved: only who owns it has.

The flag changes one more rule. With parents, a directory that already exists is fine (mkdir -p /docs twice does nothing the second time), but a file at the full path is still already_exists (AC-2.5).

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file_system.cpp
Status FileSystem::write(std::string_view path, std::string_view data, WriteMode mode) {
auto parts = split_path(path);
if (!parts.ok()) return parts.failure();
if (parts.value().empty()) return Failure{Error::is_a_directory, "/ is a directory"};
auto place = target(std::move(parts.value()));
if (!place.ok()) return place.failure();
auto& [parent, name] = place.value();
Children& children = std::get<Directory>(parent->content).children;
auto existing = children.find(name);
if (existing == children.end()) {
// A new file: build the node, bytes and all, then insert it in one
// step. Append to a missing file creates it, as >> does.
auto node = std::make_unique<Node>(Node{parent, File{std::string{data}}});
children.emplace(std::move(name), std::move(node));
return Done{};
}
auto* file = std::get_if<File>(&existing->second->content);
if (file == nullptr) {
return Failure{Error::is_a_directory, join(path_of(*parent), name) + " is a directory"};
}
// std::string promises that if assign or append throws (for example,
// out of memory), the string is left as it was. So these lines either
// change the file completely or not at all.
if (mode == WriteMode::overwrite) {
file->data.assign(data);
} else {
file->data.append(data);
}
return Done{};
}

A new file is built whole, bytes and all, and then inserted. An existing file is changed by one std::string call, and the standard library promises that assign and append leave the string as it was if they throw. So both paths are all or nothing without any extra code. read is locate and then a std::get_if<File>: a directory is is_a_directory, and the bytes are returned as a copy, which the caller then owns.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file_system.cpp
// mv checks everything first: both paths, that the source exists, that the
// destination's directory exists and the name there is free, and that a
// directory is not moving into itself. Only then does it relink the node.
Status FileSystem::mv(std::string_view from, std::string_view to) {
auto from_parts = split_path(from);
if (!from_parts.ok()) return from_parts.failure();
auto to_parts = split_path(to);
if (!to_parts.ok()) return to_parts.failure();
if (from_parts.value().empty()) return Failure{Error::is_root, "/ cannot be moved"};
if (to_parts.value().empty()) {
return Failure{Error::already_exists, "/ already exists, and mv never replaces anything"};
}
auto source = target(std::move(from_parts.value()));
if (!source.ok()) return source.failure();
Node* from_parent = source.value().parent;
Children& from_children = std::get<Directory>(from_parent->content).children;
auto entry = from_children.find(source.value().name);
if (entry == from_children.end()) {
return Failure{Error::not_found, quoted(source.value().name) + " does not exist in " +
path_of(*from_parent)};
}
Node* node = entry->second.get();
auto destination = target(std::move(to_parts.value()));
if (!destination.ok()) return destination.failure();
auto& [to_parent, to_name] = destination.value();
Children& to_children = std::get<Directory>(to_parent->content).children;
// This also refuses `mv /a /a`: the destination exists (it is the source).
if (to_children.contains(to_name)) {
return Failure{Error::already_exists,
join(path_of(*to_parent), to_name) +
" already exists, and mv never replaces anything"};
}
// A directory cannot go inside itself. Climb from the new parent to the
// root: meeting the node on the way means the new parent is the node or
// lies below it. (For a file, the climb never meets it: a file is never
// anyone's parent.)
for (const Node* up = to_parent; up != nullptr; up = up->parent) {
if (up == node) {
return Failure{Error::into_itself, path_of(*node) + " cannot move into " +
join(path_of(*to_parent), to_name) +
", which is itself or below it"};
}
}
// Commit. Nothing below allocates, so nothing below can fail.
// extract unlinks the map entry and hands it over as a "node handle";
// the Node itself stays where it is in memory.
auto handle = from_children.extract(entry);
handle.key() = std::move(to_name); // the new name, built by target() above
node->parent = to_parent; // keep the back pointer correct
// Inserting a node handle reuses its memory, so it does not allocate.
to_children.insert(std::move(handle));
return Done{};
}
How this code works: FileSystem::mv in the step 1 demo

mv /docs/notes /archive. The tree is /docs (holding notes and plan.txt) and /docs/notes/2026.

  1. Both paths split. Neither is the root.
  2. target on the source gives /docs and notes. The entry exists; node is the notes node.
  3. target on the destination gives / and archive. The root has no archive, so the name is free.
  4. The climb. up starts at the new parent, /. It is not notes, and its parent is nullptr, so the climb ends: notes is not moving into itself.
  5. Commit. extract unlinks the map entry and hands it over as a node handle; the Node object does not move in memory. handle.key() is renamed to archive (moving the string that target built, so no allocation), node->parent is set to the root, and insert puts the handle into the root’s map. Inserting a node handle reuses its memory, so it cannot run out of memory. The child 2026 still points at the same notes node, now called archive, so its parent pointer is right without being touched.

mv /archive /archive/2026/old. The source is archive in /. The destination’s directory is /archive/2026, and old is free there. The climb starts at /archive/2026, which is not the source, then goes to /archive, which is the source: refused with into_itself. Had it gone ahead, archive would own 2026, which would own archive: a cycle of owners that nothing could reach or free.

mv /docs/plan.txt /archive. The root already has archive, so already_exists. The shell’s mv would put plan.txt inside the directory; this one never replaces and never guesses (AC-5.5).

The order of checks is part of the design. “The destination exists” is checked before “into itself”, so mv /docs /docs is already_exists: the destination exists, because it is the source. And for a file, the climb can never meet the source, because a file is never anyone’s parent.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file_system.cpp
Status FileSystem::rm(std::string_view path, Recursive recursive) {
auto parts = split_path(path);
if (!parts.ok()) return parts.failure();
if (parts.value().empty()) return Failure{Error::is_root, "/ cannot be removed"};
auto place = target(std::move(parts.value()));
if (!place.ok()) return place.failure();
auto& [parent, name] = place.value();
Children& children = std::get<Directory>(parent->content).children;
auto entry = children.find(name);
if (entry == children.end()) {
return Failure{Error::not_found, quoted(name) + " does not exist in " + path_of(*parent)};
}
const auto* dir = std::get_if<Directory>(&entry->second->content);
if (dir != nullptr && !dir->children.empty() && recursive == Recursive::no) {
return Failure{Error::not_empty, join(path_of(*parent), name) +
" is not empty; remove it recursively"};
}
// Erasing the entry destroys its unique_ptr, which destroys the node
// and, through their own unique_ptrs, everything below it.
children.erase(entry);
return Done{};
}

The rules of rm, in the order the code checks them:

  1. The path must split, and rm / (or rm //, which splits to the same nothing) is is_root.
  2. The last part must be a real name, and its directory must exist (target).
  3. The entry must exist (not_found).
  4. A directory with children needs Recursive::yes (not_empty). The flag on a file or an empty directory is harmless.
  5. Then one erase. Destroying the entry’s unique_ptr destroys the node, and its map destroys its children, all the way down. There is no loop that deletes nodes one by one, and no node can be missed.

That last point has a cost the node header admits: each level of the tree is destroyed inside the destructor of the level above, so tearing down a very deep tree recurses once per level. The step 2 tests build a tree 300 levels deep and destroy it without trouble; a tree thousands of levels deep could overflow the stack. A production version would limit the depth, or take the tree apart with a loop.

Rule Where it lives
A path is absolute; // and a trailing / are ignored split_path
. stays, .. goes up, .. at the root is refused walk, rules 2 and 3
A file has nothing below it walk, rule 1
A change names a real entry target, with is_valid_name
A name is stored once the map key; Node has no name
Each node has one owner; no cycles std::unique_ptr in Children; the Node* parent
Parent pointers are right the Node{parent, …} built in mkdir and write; mv
mv never replaces, never into itself mv’s contains check and climb
A refusal changes nothing the check, build, change order in every command
ls has a fixed order std::map’s sorted keys

Take the step 1 demo from the top, and follow the tree. Each line is from the demo’s expected output; the tree is what the code leaves after it.

Command Answer Tree afterwards
mkdir /docs ok /docs
mkdir -p /docs/notes/2026 ok /docs/notes/2026
mkdir /work/src refused (not found): ‘work’ does not exist in / unchanged
echo plan > /docs/plan.txt ok adds /docs/plan.txt = plan
echo ', v2' >> /docs/plan.txt ok /docs/plan.txt = plan, v2
cat /docs/plan.txt plan, v2 unchanged
ls /docs notes/, plan.txt unchanged
mv /docs/notes /archive ok /archive/2026, /docs/plan.txt
mv /archive /archive/2026/old refused (into itself) unchanged
mv /docs/plan.txt /archive refused (already exists) unchanged
ls / archive/, docs/ unchanged
rm /archive refused (not empty) unchanged
rm -r /archive ok /docs/plan.txt
cat /docs refused (is a directory) unchanged
ls / docs/ unchanged

Three lines carry the design. mkdir /work/src is refused without parents, and /work does not appear later in ls /: the refusal left nothing behind. After mv /docs/notes /archive, the moved directory still holds 2026, and the climb in the next mv finds /archive above /archive/2026 through the parent pointer that mv set. And rm -r /archive removes 2026 with it in one erase.

The example has two steps, each a complete program with its own tests and demo:

  • Step 1 is the design above.
  • Step 2 is the change: sizes, quotas, and search. See Step 5.

Inside step 1, the order is worth copying. split_path and its tests came first, because they need no tree. Then walk and trace, so that every later bug in a path could be seen part by part. Then mkdir, write, and read, which build a tree for the other tests. Then rm, and mv last, because it has the most checks and depends on the parent pointers being right everywhere else.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// CS-17 step 1: a short scripted shell session on the in-memory file
// system. Each line shows the command as a shell would take it, then what
// the FileSystem answered.
#include <iostream>
#include <string>
#include <string_view>
#include "file_system.hpp"
using namespace memfs;
namespace {
// Prints "ok", or the code and reason of a refusal.
void show(std::string_view command, const Status& status) {
std::cout << "$ " << command << '\n';
if (status.ok()) {
std::cout << " ok\n";
} else {
std::cout << " refused (" << to_string(status.error()) << "): " << status.reason() << '\n';
}
}
void show_ls(const FileSystem& fs, std::string_view path) {
std::cout << "$ ls " << path << '\n';
auto listed = fs.ls(path);
if (!listed.ok()) {
std::cout << " refused (" << to_string(listed.error()) << "): " << listed.reason() << '\n';
return;
}
for (const Entry& entry : listed.value()) {
std::cout << " " << entry.name << (entry.kind == Kind::directory ? "/" : "") << '\n';
}
}
void show_cat(const FileSystem& fs, std::string_view path) {
std::cout << "$ cat " << path << '\n';
auto text = fs.read(path);
if (text.ok()) {
std::cout << " " << text.value() << '\n';
} else {
std::cout << " refused (" << to_string(text.error()) << "): " << text.reason() << '\n';
}
}
void show_trace(const FileSystem& fs, std::string_view path) {
std::cout << "$ trace " << path << '\n';
for (const Step& step : fs.trace(path)) {
std::cout << " " << step.part << " -> " << step.outcome << '\n';
}
}
} // namespace
int main() {
FileSystem fs;
show("mkdir /docs", fs.mkdir("/docs"));
show("mkdir -p /docs/notes/2026", fs.mkdir("/docs/notes/2026", Parents::create));
show("mkdir /work/src", fs.mkdir("/work/src"));
show("echo plan > /docs/plan.txt", fs.write("/docs/plan.txt", "plan"));
show("echo ', v2' >> /docs/plan.txt", fs.write("/docs/plan.txt", ", v2", WriteMode::append));
show_cat(fs, "/docs/plan.txt");
show_ls(fs, "/docs");
show_trace(fs, "/docs//notes/./2026/../../plan.txt");
show_trace(fs, "/docs/../..");
show("mv /docs/notes /archive", fs.mv("/docs/notes", "/archive"));
show("mv /archive /archive/2026/old", fs.mv("/archive", "/archive/2026/old"));
show("mv /docs/plan.txt /archive", fs.mv("/docs/plan.txt", "/archive"));
show_ls(fs, "/");
show("rm /archive", fs.rm("/archive"));
show("rm -r /archive", fs.rm("/archive", Recursive::yes));
show_cat(fs, "/docs");
show_ls(fs, "/");
return 0;
}
Expected output
$ mkdir /docs
ok
$ mkdir -p /docs/notes/2026
ok
$ mkdir /work/src
refused (not found): 'work' does not exist in /
$ echo plan > /docs/plan.txt
ok
$ echo ', v2' >> /docs/plan.txt
ok
$ cat /docs/plan.txt
plan, v2
$ ls /docs
notes/
plan.txt
$ trace /docs//notes/./2026/../../plan.txt
/ -> /
docs -> /docs
notes -> /docs/notes
. -> /docs/notes
2026 -> /docs/notes/2026
.. -> /docs/notes
.. -> /docs
plan.txt -> /docs/plan.txt
$ trace /docs/../..
/ -> /
docs -> /docs
.. -> /
.. -> error: '..' at / would go above the root, which has no parent
$ mv /docs/notes /archive
ok
$ mv /archive /archive/2026/old
refused (into itself): /archive cannot move into /archive/2026/old, which is itself or below it
$ mv /docs/plan.txt /archive
refused (already exists): /archive already exists, and mv never replaces anything
$ ls /
archive/
docs/
$ rm /archive
refused (not empty): /archive is not empty; remove it recursively
$ rm -r /archive
ok
$ cat /docs
refused (is a directory): /docs is a directory
$ ls /
docs/

The tests are named after the acceptance criteria. Four helpers make them short: names lists a directory as one string, snapshot prints the whole tree with every file’s bytes, traced prints a trace, and build makes the small tree that most tests start from.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
// The names in a directory as one string, directories marked with '/':
// "a.txt docs/". "?" and the error if ls refused.
std::string names(const FileSystem& fs, std::string_view path) {
auto listed = fs.ls(path);
if (!listed.ok()) return "?" + std::string{to_string(listed.error())};
std::string out;
for (const Entry& entry : listed.value()) {
if (!out.empty()) out += ' ';
out += entry.name;
if (entry.kind == Kind::directory) out += '/';
}
return out;
}
// The whole tree as text: every path, and each file's bytes. Two equal
// snapshots mean the tree did not change. The recursion is fine here: the
// test trees are a few levels deep.
std::string snapshot(const FileSystem& fs, const std::string& path = "/") {
std::string out;
for (const Entry& entry : fs.ls(path).value()) {
std::string child = join(path, entry.name);
if (entry.kind == Kind::directory) {
out += child + "/\n" + snapshot(fs, child);
} else {
out += child + " = " + fs.read(child).value() + "\n";
}
}
return out;
}
// A trace as one string: "part>outcome" pairs separated by " | ".
std::string traced(const FileSystem& fs, std::string_view path) {
std::string out;
for (const Step& step : fs.trace(path)) {
if (!out.empty()) out += " | ";
out += step.part + ">" + step.outcome;
}
return out;
}
// /docs/a.txt, /docs/notes/b.txt, /tmp
void build(FileSystem& fs) {
LLD_CHECK(fs.mkdir("/docs").ok());
LLD_CHECK(fs.mkdir("/docs/notes").ok());
LLD_CHECK(fs.mkdir("/tmp").ok());
LLD_CHECK(fs.write("/docs/a.txt", "alpha").ok());
LLD_CHECK(fs.write("/docs/notes/b.txt", "beta").ok());
}

snapshot is the strongest check in the file. A test takes a snapshot, makes a series of commands that must all be refused, and takes another. If the two strings are equal, no refusal changed anything, which is how FR-7 and INV-5 are tested without writing one check per node.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_1_1_paths_must_be_absolute_and_not_empty) {
FileSystem fs;
LLD_CHECK_EQ(fs.mkdir("docs").error(), Error::invalid_path);
LLD_CHECK_EQ(fs.mkdir("").error(), Error::invalid_path);
LLD_CHECK_EQ(fs.read("a.txt").error(), Error::invalid_path);
LLD_CHECK_EQ(fs.mkdir(std::string_view{"/a\0b", 4}).error(), Error::invalid_path);
LLD_CHECK_EQ(names(fs, "/"), "");
}
LLD_TEST(ac_1_2_repeated_and_trailing_slashes_are_ignored) {
FileSystem fs;
build(fs);
LLD_CHECK_EQ(fs.read("//docs///a.txt").value(), "alpha");
LLD_CHECK_EQ(names(fs, "/docs/notes/"), "b.txt");
LLD_CHECK(fs.mkdir("/tmp//x/").ok());
LLD_CHECK_EQ(names(fs, "/tmp"), "x/");
}
LLD_TEST(ac_1_3_dot_stays_and_dot_dot_goes_to_the_parent) {
FileSystem fs;
build(fs);
LLD_CHECK_EQ(fs.read("/docs/./notes/../a.txt").value(), "alpha");
LLD_CHECK_EQ(fs.read("/docs/notes/../../docs/notes/b.txt").value(), "beta");
LLD_CHECK_EQ(names(fs, "/docs/.."), "docs/ tmp/");
LLD_CHECK(fs.write("/tmp/../docs/./c.txt", "gamma").ok());
LLD_CHECK_EQ(fs.read("/docs/c.txt").value(), "gamma");
}
LLD_TEST(ac_1_4_dot_dot_above_the_root_is_refused) {
FileSystem fs;
build(fs);
LLD_CHECK_EQ(fs.ls("/..").error(), Error::invalid_path);
LLD_CHECK_EQ(fs.read("/docs/../../docs/a.txt").error(), Error::invalid_path);
LLD_CHECK_EQ(fs.mkdir("/../x").error(), Error::invalid_path);
}
LLD_TEST(ac_1_5_a_file_has_no_parts_below_it) {
FileSystem fs;
build(fs);
LLD_CHECK_EQ(fs.read("/docs/a.txt/x").error(), Error::not_a_directory);
LLD_CHECK_EQ(fs.ls("/docs/a.txt/..").error(), Error::not_a_directory);
LLD_CHECK_EQ(fs.ls("/docs/a.txt/.").error(), Error::not_a_directory);
LLD_CHECK_EQ(fs.read("/docs/missing/..").error(), Error::not_found);
}
LLD_TEST(ac_1_6_names_are_not_empty_dots_or_holding_a_slash) {
LLD_CHECK(is_valid_name("a.txt"));
LLD_CHECK(is_valid_name("..."));
LLD_CHECK(!is_valid_name(""));
LLD_CHECK(!is_valid_name("."));
LLD_CHECK(!is_valid_name(".."));
LLD_CHECK(!is_valid_name("a/b"));
LLD_CHECK(!is_valid_name(std::string_view{"a\0b", 3}));
}
LLD_TEST(ac_1_7_a_change_must_name_its_entry_with_a_real_name) {
FileSystem fs;
build(fs);
const std::string before = snapshot(fs);
LLD_CHECK_EQ(fs.mkdir("/docs/..").error(), Error::invalid_path);
LLD_CHECK_EQ(fs.mkdir("/docs/.").error(), Error::invalid_path);
LLD_CHECK_EQ(fs.write("/docs/notes/..", "x").error(), Error::invalid_path);
LLD_CHECK_EQ(fs.rm("/docs/notes/..", Recursive::yes).error(), Error::invalid_path);
LLD_CHECK_EQ(fs.mv("/docs/.", "/tmp/d").error(), Error::invalid_path);
LLD_CHECK_EQ(fs.mv("/docs/a.txt", "/tmp/.").error(), Error::invalid_path);
LLD_CHECK_EQ(snapshot(fs), before);
}
LLD_TEST(ac_1_8_trace_shows_each_part_and_where_it_leads) {
FileSystem fs;
build(fs);
LLD_CHECK_EQ(traced(fs, "/docs//./notes/../notes/b.txt"),
"/>/ | docs>/docs | .>/docs | notes>/docs/notes | ..>/docs | "
"notes>/docs/notes | b.txt>/docs/notes/b.txt");
LLD_CHECK_EQ(traced(fs, "/"), "/>/");
LLD_CHECK_EQ(traced(fs, "/docs/nope/x"),
"/>/ | docs>/docs | nope>error: 'nope' does not exist in /docs");
LLD_CHECK_EQ(traced(fs, "/.."), "/>/ | ..>error: '..' at / would go above the root, "
"which has no parent");
LLD_CHECK_EQ(traced(fs, "/docs/a.txt/.."),
"/>/ | docs>/docs | a.txt>/docs/a.txt | ..>error: /docs/a.txt is a file, "
"so it has no '..'");
LLD_CHECK_EQ(traced(fs, "docs"), "docs>error: 'docs' does not start with '/' "
"(paths are absolute)");
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step1.cpp
LLD_TEST(ac_5_1_mv_renames_in_place) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.mv("/docs/a.txt", "/docs/z.txt").ok());
LLD_CHECK_EQ(names(fs, "/docs"), "notes/ z.txt");
LLD_CHECK_EQ(fs.read("/docs/z.txt").value(), "alpha");
LLD_CHECK(fs.mv("/docs/notes", "/docs/n").ok());
LLD_CHECK_EQ(fs.read("/docs/n/b.txt").value(), "beta");
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_5_2_mv_moves_a_directory_with_everything_below_it) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.mv("/docs/notes", "/tmp/kept").ok());
LLD_CHECK_EQ(names(fs, "/docs"), "a.txt");
LLD_CHECK_EQ(fs.read("/tmp/kept/b.txt").value(), "beta");
// ".." from the moved directory now leads to its new parent.
LLD_CHECK_EQ(names(fs, "/tmp/kept/.."), "kept/");
LLD_CHECK_EQ(traced(fs, "/tmp/kept/b.txt/../.."),
"/>/ | tmp>/tmp | kept>/tmp/kept | b.txt>/tmp/kept/b.txt | "
"..>error: /tmp/kept/b.txt is a file, so it has no '..'");
LLD_CHECK_EQ(traced(fs, "/tmp/kept/.."), "/>/ | tmp>/tmp | kept>/tmp/kept | ..>/tmp");
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_5_3_mv_moves_up_and_across) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.mv("/docs/notes/b.txt", "/b.txt").ok());
LLD_CHECK(fs.mv("/docs", "/tmp/docs").ok());
LLD_CHECK(fs.mv("/tmp/docs/notes", "/notes").ok());
LLD_CHECK_EQ(snapshot(fs), "/b.txt = beta\n/notes/\n/tmp/\n/tmp/docs/\n"
"/tmp/docs/a.txt = alpha\n");
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_5_4_mv_refuses_a_directory_into_itself_or_below_it) {
FileSystem fs;
build(fs);
const std::string before = snapshot(fs);
LLD_CHECK_EQ(fs.mv("/docs", "/docs/inner").error(), Error::into_itself);
LLD_CHECK_EQ(fs.mv("/docs", "/docs/notes/inner").error(), Error::into_itself);
LLD_CHECK_EQ(fs.mv("/docs", "/docs/notes/../x").error(), Error::into_itself);
LLD_CHECK_EQ(snapshot(fs), before);
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_5_5_mv_never_replaces_an_existing_entry) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.write("/tmp/a.txt", "other").ok());
const std::string before = snapshot(fs);
LLD_CHECK_EQ(fs.mv("/docs/a.txt", "/tmp/a.txt").error(), Error::already_exists); // file
LLD_CHECK_EQ(fs.mv("/docs/a.txt", "/tmp").error(), Error::already_exists); // a directory
LLD_CHECK_EQ(fs.mv("/docs", "/docs").error(), Error::already_exists); // itself
LLD_CHECK_EQ(fs.mv("/docs", "/").error(), Error::already_exists); // the root
LLD_CHECK_EQ(snapshot(fs), before);
}
LLD_TEST(ac_5_6_mv_refuses_bad_sources_and_destinations) {
FileSystem fs;
build(fs);
const std::string before = snapshot(fs);
LLD_CHECK_EQ(fs.mv("/nope", "/x").error(), Error::not_found);
LLD_CHECK_EQ(fs.mv("/docs/a.txt", "/nope/a.txt").error(), Error::not_found);
LLD_CHECK_EQ(fs.mv("/docs/a.txt", "/docs/notes/b.txt/a").error(), Error::not_a_directory);
LLD_CHECK_EQ(fs.mv("/", "/x").error(), Error::is_root);
LLD_CHECK_EQ(fs.mv("docs", "/x").error(), Error::invalid_path);
LLD_CHECK_EQ(fs.mv("/docs", "x").error(), Error::invalid_path);
LLD_CHECK_EQ(snapshot(fs), before);
}

The mv tests check three things after each move: the names where the node went and where it left, the bytes of a file below it, and .. from the moved directory (through names and traced), which only works if the parent pointer was set. Most end with consistent(), which walks the whole tree and checks every parent pointer and name (INV-2, INV-3).

What the tests do not cover: no test makes memory run out, so the claim that an out-of-memory error leaves the tree unchanged (NFR-2) rests on reading the code and the standard library’s guarantees, not on a run. The agent that wrote the example reported a mutation check of both steps, 24 of 25 mutants made a test fail, and the survivor was a change inside consistent(), which only the tests use; that check was not rerun for this page.

The six flawed sketches on this page were compiled syntax-only with g++ 11.4 and clang++ 14 (-std=c++20 -Wall -Wextra, against the step 1 or step 2 headers, the bare commit fragment wrapped in a function), with no errors or warnings. They were not run: what each one gets wrong comes from reading the code.

The last step takes a change to the requirements and shows which parts of the design move and which stay.

“Two things. People keep filling the sandbox, so we need to see how big a directory is and put a limit on some of them, say 16 bytes for a test folder. Nothing may ever go over a limit, however it gets there. And people want find: give a starting directory and a name pattern like *.txt, and get every match below it, in an order that does not change from one run to the next.”

Clarified with the team:

Question Answer What it changes
What is a directory’s size? The bytes of every file anywhere below it. A directory itself is free. mkdir never changes a size.
Does a limit on /docs count files in /docs/notes? Yes, everything below. A write must check every directory from its parent up to the root.
May a limit be set lower than what is already there? No: refuse it. “No directory is over its limit” is true at every moment.
Does a move count against the limit? Yes, if the bytes come from outside the limited directory. mv checks the destination, but only where totals grow.
What patterns? * for any run of characters, ? for one. Whole names, case matters. A small matcher, no regular expressions.
Which order for find? A directory, then what is in it, then its next sibling, in name order. Depth first, children in map order.

UC-1 … UC-7 and their tests stay as they are, and run again in step 2 (the step 2 test file repeats them).

UC-8 Sizes.

  • AC-8.1 A file’s size is its byte count; a directory’s is the sum of the files below it (/docs is 9 for alpha and beta), and an empty directory is 0. New directories add nothing.
  • AC-8.2 write and append keep every total right, both when a file grows and when it shrinks.
  • AC-8.3 mv carries the bytes to the new place; a rename changes no total.
  • AC-8.4 rm takes the bytes away.
  • AC-8.5 ls shows each entry’s size.

UC-9 Quotas.

  • AC-9.1 A quota goes on a directory (a file is not_a_directory) that holds no more than the quota; a quota exactly at the total is fine.
  • AC-9.2 A write, overwrite, or append that would go over is refused (quota_exceeded) and changes nothing; up to the quota exactly is fine.
  • AC-9.3 Every quota on the way to the root counts, and the refusal names the lowest directory that would go over.
  • AC-9.4 Shrinking, or staying the same size, is always allowed, even in a full directory.
  • AC-9.5 A quota of 0 allows only empty files, and removing the quota lifts the limit.
  • AC-9.6 mv checks the quotas at the destination, and a refused mv changes nothing.
  • AC-9.7 mv inside a full directory is allowed, because its total does not change; a quota below the shared directory still counts.

UC-10 Search by name.

  • AC-10.1 The order is depth first, a directory before its contents, children in name order, and the same on every run.
  • AC-10.2 Patterns match files and directories.
  • AC-10.3 Only what is below the start is searched, never the start itself.
  • AC-10.4 An empty pattern or one holding / is invalid_pattern; a file as the start is not_a_directory.
  • AC-10.5 Search sees moves and removals.
  • AC-10.6 Search reaches the bottom of a tree 300 levels deep.

UC-11 Patterns.

  • AC-11.1 A pattern matches the whole name: * matches any run, including none; ? exactly one character; anything else itself. A * in the pattern is a wildcard even where the name holds a real *.

The new invariants:

  • INV-6 The cached sizes are right. Every directory’s bytes equals the sum of the files below it. Kept by add_bytes and remove_bytes, called by write, mv, and rm after their change. Checked by consistent.
  • INV-7 No directory is over its quota. Kept by set_quota, which refuses a quota below the total, and by check_room, called before every change that adds bytes. Checked by consistent.
File Change
node.hpp Directory gains bytes and quota
result.hpp two new codes, quota_exceeded and invalid_pattern
file_system.hpp Entry gains size; new size, set_quota, search
file_system.cpp check_room, add_bytes, remove_bytes; a check and an update in write, mv, rm; search; a second pass in consistent
pattern.hpp, .cpp new: matches

split_path, walk, target, mkdir, read, and the Result type did not change. The path and ownership design carried the change without a single edit, which is a fair test of it.

struct Directory

Data members

  • Children children; public, as in step 1
  • std::size_t bytes = 0; public; cached: all file bytes below
  • std::optional<std::size_t> quota; public; empty means no limit

class FileSystem

Member functions

  • Result<std::size_t> size(std::string_view path) const;
  • Status set_quota(std::string_view path, std::optional<std::size_t> limit);
  • Result<std::vector<std::string>> search(std::string_view start, std::string_view pattern) const;

struct Entry

Data members

  • std::string name; public
  • Kind kind; public
  • std::size_t size; public; new in step 2

namespace memfs

Functions

  • Status check_room(const Node& dir, std::size_t extra, const Node* stop = nullptr); file_system.cpp
  • void add_bytes(Node& dir, std::size_t amount) noexcept; file_system.cpp
  • void remove_bytes(Node& dir, std::size_t amount) noexcept; file_system.cpp
  • bool matches(std::string_view name, std::string_view pattern) noexcept; pattern.hpp
What step 2 adds. Directory and FileSystem show only the new members; the namespace box lists the helpers in file_system.cpp and pattern.hpp

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

node.hpp
// Step 2: a directory also keeps the total size below it, and may have a
// quota.
//
// The size rule: a file's size is its byte count. A directory's size is
// the sum of the sizes of all files anywhere below it; a directory itself
// counts 0 bytes, so mkdir never changes a size.
//
// That sum is cached in `bytes`, not computed when asked. A write must
// check the quota of every directory on the way up to the root, and
// computing each of those sums would visit whole subtrees on every write.
// The cost of the cache: every change to the bytes below a directory must
// update it. Only four operations change bytes (write, append, mv, rm), and
// each adds or subtracts the same amount on every directory from the
// changed entry's parent up to the root. FileSystem::consistent recomputes
// all the sums so the tests can check the cache.
struct Directory {
Children children;
std::size_t bytes = 0; // cached: all file bytes below this directory
std::optional<std::size_t> quota; // the most `bytes` may reach; empty means no limit
};

There are two ways to know a directory’s size: add up its files when asked, or keep a running total and update it on every change.

write now works out how many bytes it adds before it changes anything. For append, that is all of data; for an overwrite, the difference, and only if the file grows. A file that shrinks, or stays the same size, cannot break a quota, so it is never checked (AC-9.4). rm reads the size of what it removes, subtracts it up to the root, and only then erases the node, while it still exists to be asked.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file_system.cpp
// Step 2. Checks that `extra` more bytes fit under the quota of every
// directory from `dir` up to the root, or, if `stop` is given, up to but
// not including `stop` (mv uses it: from there up, the totals do not
// change). Refuses with quota_exceeded, naming the lowest directory that
// would go over. Changes nothing either way.
Status check_room(const Node& dir, std::size_t extra, const Node* stop = nullptr) {
for (const Node* at = &dir; at != nullptr && at != stop; at = at->parent) {
// Every node above another is a directory, so get_if never gives
// nullptr here.
const Directory& d = *std::get_if<Directory>(&at->content);
// `extra > quota - bytes` rather than `bytes + extra > quota`: bytes
// never exceeds the quota, so the subtraction cannot go below zero,
// and there is no sum that could overflow.
if (d.quota && extra > *d.quota - d.bytes) {
return Failure{Error::quota_exceeded,
path_of(*at) + " holds " + std::to_string(d.bytes) + " of its " +
std::to_string(*d.quota) + " bytes; " + std::to_string(extra) +
" more would not fit"};
}
}
return Done{};
}

Two details in check_room carry INV-7. It climbs every directory up to the root, because a quota on /docs limits the files in /docs/notes too. And it compares extra > quota - bytes, not bytes + extra > quota. Because no directory is ever over its quota, quota - bytes cannot go below zero, and there is no sum that could wrap around for a huge extra.

Why mv checks only below the shared directory. A move takes bytes out of every directory above the old place and puts them into every directory above the new one. A directory above both places loses and gains the same amount, so its total does not change, and its quota cannot be broken by the move, even if it is full. mv finds the lowest such directory and passes it to check_room as stop.

How this code works: The two mv commands in the step 2 demo

Before them, /docs has a quota of 16 and holds 16: plan.txt (8 bytes, plan, v2) and notes/todo.txt (8 bytes, call Sam). /work holds plan.txt, 5 bytes (draft).

mv /work/plan.txt /docs/notes/plan.txt moves 5 bytes.

  1. The old parent is /work, the new parent /docs/notes.

  2. Find the shared directory. Start at /docs/notes: is it /work or above it? No. /docs? No. /? Yes. So shared is the root.

  3. Check up to, not including, the root.

    Directory bytes quota 5 more fit?
    /docs/notes 8 none yes
    /docs 16 16 no: 5 > 0
  4. Refused, before any change: “/docs holds 16 of its 16 bytes; 5 more would not fit”.

mv /docs/plan.txt /docs/notes/old-plan.txt moves 8 bytes.

  1. The old parent is /docs, the new parent /docs/notes.
  2. Start at /docs/notes: is it /docs or above it? No. Its parent /docs: yes. So shared is /docs.
  3. Only /docs/notes is checked. It has no quota, so the move is allowed, although /docs is full: the bytes stay inside it.
  4. The totals. remove_bytes(/docs, 8) takes 8 from /docs (16 to 8) and from / (21 to 13). add_bytes(/docs/notes, 8) adds 8 to /docs/notes (8 to 16), /docs (8 to 16), and / (13 to 21). Above the shared directory, the two cancel out.

The demo’s next ls /docs/notes shows old-plan.txt and todo.txt, 8 bytes each.

set_quota closes the last gap: a quota below what a directory already holds is refused, so the rule “no directory is over its quota” is true at every moment, and no write ever starts from a directory that is already over.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file_system.cpp
bool FileSystem::consistent() const {
if (root_.parent != nullptr) return false;
// First pass: list every node, each directory before its children,
// using a list of nodes still to visit instead of recursion, so a deep
// tree cannot overflow the call stack. Check the parent pointers on
// the way.
std::vector<const Node*> order;
std::vector<const Node*> pending{&root_};
while (!pending.empty()) {
const Node* at = pending.back();
pending.pop_back();
order.push_back(at);
const auto* dir = std::get_if<Directory>(&at->content);
if (dir == nullptr) continue;
for (const auto& [name, child] : dir->children) {
if (child == nullptr || child->parent != at || !is_valid_name(name)) return false;
pending.push_back(child.get());
}
}
// Second pass, backwards: a node is listed after its parent, so going
// backwards finishes every child before its parent. Each node adds its
// total to its parent's sum; a directory's sum is then complete when it
// is reached, and must equal its cached bytes and fit its quota.
std::unordered_map<const Node*, std::size_t> sums;
for (auto it = order.rbegin(); it != order.rend(); ++it) {
const Node* at = *it;
std::size_t total = 0;
if (const auto* file = std::get_if<File>(&at->content)) {
total = file->data.size();
} else {
const auto& dir = std::get<Directory>(at->content);
total = sums[at]; // 0 if nothing below added to it
if (dir.bytes != total) return false;
if (dir.quota && total > *dir.quota) return false;
}
if (at->parent != nullptr) sums[at->parent] += total;
}
return true;
}
How this code works: FileSystem::consistent on the test tree

The tree from build: /docs/a.txt (5 bytes), /docs/notes/b.txt (4 bytes), and an empty /tmp.

  1. First pass: list every node, parents first. pending is a stack. The root is popped and listed, and its children docs and tmp pushed in name order, so tmp is on top and popped next. Then docs, which pushes a.txt and notes; then notes, which pushes b.txt; then b.txt, then a.txt. order ends as /, /tmp, /docs, /docs/notes, /docs/notes/b.txt, /docs/a.txt. Each node is listed after its parent, because a child is pushed only when its parent is popped. The parent pointers and names are checked on the way.

  2. Second pass: backwards. Going from the end, every child comes before its parent, so each directory’s sum is complete when it is reached.

    Node Its total Check Adds to
    /docs/a.txt 5 (a file) /docs: 5
    /docs/notes/b.txt 4 (a file) /docs/notes: 4
    /docs/notes sums gives 4 bytes is 4: ok /docs: 9
    /docs sums gives 9 bytes is 9: ok /: 9
    /tmp sums gives 0 bytes is 0: ok /: 9
    / sums gives 9 bytes is 9: ok (no parent)
  3. sums[at] on a directory that nothing added to (/tmp) inserts a 0 and returns it, which is the right total for an empty directory.

This is the function that the reported mutation check could not fully pin down: one mutant inside it survived. That is a weakness of a check used only by tests, which no test checks in turn; it does not affect the file system’s own behaviour.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

pattern.hpp
// True if the whole of `name` matches `pattern`. Matching is case-sensitive.
// '*' matches any run of characters, including none
// '?' matches exactly one character
// any other character matches only itself
// A pattern with no '*' or '?' is therefore an exact match. There is no
// escape: a name holding a real '*' can be matched only by a wildcard.
// matches("notes.txt", "*.txt") == true
// matches("a.txt", "?.txt") == true
// matches("ab.txt", "?.txt") == false
// No recursion and no allocation: the loop keeps the position of the last
// '*' and, when the rest fails, retries with the '*' taking one more
// character. The work is at most about name.size() * pattern.size().
[[nodiscard]] bool matches(std::string_view name, std::string_view pattern) noexcept;
How this code works: matches('aab', '*ab'), where the star must give a character back

n is the next character of the name, p of the pattern; star is where the last * is, and star_took the place in the name just after what that * has taken so far. The code tests for * first, so a * in the pattern is always a wildcard, even against a real * in a name.

Step n p What happens
1 0 0 *: remember star = 0, star_took = 0, try it taking nothing
2 0 1 a matches a
3 1 2 a against b: mismatch; the star takes one more: n = 1, p = 1
4 1 1 a matches a
5 2 2 b matches b
6 3 3 the name is used up, and so is the pattern: a match

A version that let the * grab as much as it could and never gave it back would fail here; AC-11.1 tests exactly this case.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

file_system.cpp
// Visitor or a plain function? A Visitor (an accept function on every node
// class, and a visitor class with one visit function per kind) earns its
// keep with Composite: many node classes, and new operations added from
// outside without editing them. Here the node kinds sit in a std::variant,
// so std::get_if already says which kind a node is, and search needs only
// "if it is a directory, look inside". A Visitor would add two class
// hierarchies and nothing that search uses, so this is a plain function.
//
// It is written as a loop with a stack of nodes still to visit, not as a
// function that calls itself: the depth of the tree then costs heap memory
// in `pending`, not call-stack frames, so a deep tree cannot overflow the
// stack. The order is the one a recursive walk would give.
Result<std::vector<std::string>> FileSystem::search(std::string_view start,
std::string_view pattern) const {
if (pattern.empty() || pattern.find('/') != std::string_view::npos) {
return Failure{Error::invalid_pattern,
"a pattern matches one name, so it cannot be empty or hold '/'"};
}
auto found = locate(start);
if (!found.ok()) return found.failure();
const auto* top = std::get_if<Directory>(&found.value()->content);
if (top == nullptr) {
return Failure{Error::not_a_directory,
path_of(*found.value()) + " is a file; search starts in a directory"};
}
// A node still to visit, with its name (a view of the key in its
// parent's map, valid while the tree is unchanged) and its full path.
struct Pending {
const Node* node;
std::string_view name;
std::string path;
};
std::vector<Pending> pending;
// Pushes a directory's children in reverse name order, so that the
// smallest name ends up on top of the stack and is visited first.
auto push_children = [&pending](const Directory& dir, const std::string& path) {
for (auto child = dir.children.rbegin(); child != dir.children.rend(); ++child) {
pending.push_back(Pending{child->second.get(), child->first, join(path, child->first)});
}
};
std::vector<std::string> hits;
push_children(*top, path_of(*found.value()));
while (!pending.empty()) {
Pending next = std::move(pending.back()); // take the top, then drop it from the stack
pending.pop_back();
if (matches(next.name, pattern)) hits.push_back(next.path);
// Its children go on top, so they are visited before its siblings:
// a directory comes before everything inside it.
if (const auto* dir = std::get_if<Directory>(&next.node->content)) {
push_children(*dir, next.path);
}
}
return hits;
}
How this code works: FileSystem::search('/', 'x') in test ac_10_1

The tree: directories /a, /a/b, /a-c, and empty files /a/x, /a/b/x, /a/b/y.txt, /a-c/x, and /x. In byte order a sorts before a-c, which sorts before x.

  1. Start. push_children pushes the root’s children in reverse name order, /x, /a-c, /a, so the smallest name, /a, is on top.

  2. The loop pops the top, tests its name, and, for a directory, pushes its children the same way. They land on top of its siblings, so they are visited first.

    Popped Matches x? Pushed Stack afterwards, top last
    /a no /a/x, /a/b /x, /a-c, /a/x, /a/b
    /a/b no /a/b/y.txt, /a/b/x /x, /a-c, /a/x, /a/b/y.txt, /a/b/x
    /a/b/x yes (a file) /x, /a-c, /a/x, /a/b/y.txt
    /a/b/y.txt no (a file) /x, /a-c, /a/x
    /a/x yes (a file) /x, /a-c
    /a-c no /a-c/x /x, /a-c/x
    /a-c/x yes (a file) /x
    /x yes (a file) empty
  3. The answer is /a/b/x, /a/x, /a-c/x, /x, the order the test expects. All of /a comes before /a-c, even though the string /a-c sorts before /a/b, because a directory’s contents are visited before its next sibling.

  4. Pending::name is a std::string_view of the key in the parent’s map. It stays valid because search is const and nothing changes the tree while it runs.

  5. The depth costs heap memory, not stack. A tree 300 levels deep (AC-10.6) makes the stack vector deeper, not the call stack.

Visitor, or this loop? The curriculum offered a choice, and the code comment gives the verdict. A Visitor pays off when there are many node classes in a hierarchy and new operations are added from outside without editing those classes. Here there is one Node type with a two-way variant, and search needs only “if it is a directory, look inside”. A Visitor would add an accept function, a visitor interface, and a search visitor class, and nothing that search uses. If the design were Composite with many kinds of node, and the team kept adding operations like search, size reports, and backups, a Visitor (or std::visit over a larger variant) would start to earn its place. See Visitor for that case.

A recursive function would also have been fine for the trees in the tests, and shorter. The loop was chosen so that the depth of the tree can never overflow the call stack, and it keeps the same order a recursive walk would give.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// The size of `path`, or a huge number (that no test expects) if refused.
std::size_t size_at(const FileSystem& fs, std::string_view path) {
auto size = fs.size(path);
return size.ok() ? size.value() : static_cast<std::size_t>(-1);
}
LLD_TEST(ac_8_1_a_directory_is_the_sum_of_the_files_below_it) {
FileSystem fs;
build(fs); // a.txt is "alpha" (5 bytes), notes/b.txt is "beta" (4)
LLD_CHECK_EQ(size_at(fs, "/docs/a.txt"), 5u);
LLD_CHECK_EQ(size_at(fs, "/docs/notes"), 4u);
LLD_CHECK_EQ(size_at(fs, "/docs"), 9u);
LLD_CHECK_EQ(size_at(fs, "/"), 9u);
LLD_CHECK_EQ(size_at(fs, "/tmp"), 0u);
LLD_CHECK(fs.mkdir("/docs/x/y", Parents::create).ok()); // directories add nothing
LLD_CHECK_EQ(size_at(fs, "/docs"), 9u);
LLD_CHECK_EQ(fs.size("/nope").error(), Error::not_found);
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_8_2_write_and_append_keep_every_total_right) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.write("/docs/notes/b.txt", "longer text").ok()); // 4 -> 11
LLD_CHECK_EQ(size_at(fs, "/docs/notes"), 11u);
LLD_CHECK_EQ(size_at(fs, "/"), 16u);
LLD_CHECK(fs.write("/docs/notes/b.txt", "x").ok()); // 11 -> 1: totals shrink
LLD_CHECK_EQ(size_at(fs, "/docs"), 6u);
LLD_CHECK(fs.write("/docs/notes/b.txt", "yz", WriteMode::append).ok()); // 1 -> 3
LLD_CHECK(fs.write("/docs/notes/c.txt", "1234").ok()); // new: +4
LLD_CHECK_EQ(size_at(fs, "/docs/notes"), 7u);
LLD_CHECK_EQ(size_at(fs, "/"), 12u);
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_8_3_mv_carries_the_bytes_to_the_new_place) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.mv("/docs/notes", "/tmp/notes").ok());
LLD_CHECK_EQ(size_at(fs, "/docs"), 5u);
LLD_CHECK_EQ(size_at(fs, "/tmp"), 4u);
LLD_CHECK_EQ(size_at(fs, "/"), 9u);
LLD_CHECK(fs.mv("/docs/a.txt", "/tmp/notes/a.txt").ok());
LLD_CHECK_EQ(size_at(fs, "/docs"), 0u);
LLD_CHECK_EQ(size_at(fs, "/tmp/notes"), 9u);
LLD_CHECK(fs.mv("/tmp/notes", "/tmp/renamed").ok()); // a rename changes no total
LLD_CHECK_EQ(size_at(fs, "/tmp"), 9u);
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_8_4_rm_takes_the_bytes_away) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.rm("/docs/a.txt").ok());
LLD_CHECK_EQ(size_at(fs, "/docs"), 4u);
LLD_CHECK(fs.rm("/docs", Recursive::yes).ok());
LLD_CHECK_EQ(size_at(fs, "/"), 0u);
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_8_5_ls_shows_each_size) {
FileSystem fs;
build(fs);
const auto listed = fs.ls("/docs");
LLD_CHECK_EQ(listed.value().size(), 2u);
LLD_CHECK_EQ(listed.value()[0].name, "a.txt");
LLD_CHECK_EQ(listed.value()[0].size, 5u);
LLD_CHECK_EQ(listed.value()[1].name, "notes");
LLD_CHECK_EQ(listed.value()[1].size, 4u);
const auto file = fs.ls("/docs/a.txt"); // named, so the entry outlives the check
LLD_CHECK_EQ(file.value()[0].size, 5u);
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
LLD_TEST(ac_9_1_a_quota_goes_on_a_directory_that_is_within_it) {
FileSystem fs;
build(fs);
LLD_CHECK_EQ(fs.set_quota("/docs/a.txt", 10).error(), Error::not_a_directory);
LLD_CHECK_EQ(fs.set_quota("/nope", 10).error(), Error::not_found);
LLD_CHECK_EQ(fs.set_quota("/docs", 8).error(), Error::quota_exceeded); // holds 9
LLD_CHECK(fs.set_quota("/docs", 9).ok()); // exactly full
LLD_CHECK(fs.set_quota("/", 100).ok());
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_9_2_a_write_over_the_quota_is_refused_and_changes_nothing) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.set_quota("/docs/notes", 6).ok()); // holds 4
const std::string before = snapshot(fs);
LLD_CHECK_EQ(fs.write("/docs/notes/c.txt", "xyz").error(), Error::quota_exceeded);
LLD_CHECK_EQ(fs.write("/docs/notes/b.txt", "1234567").error(), Error::quota_exceeded);
LLD_CHECK_EQ(fs.write("/docs/notes/b.txt", "xyz", WriteMode::append).error(),
Error::quota_exceeded);
LLD_CHECK_EQ(snapshot(fs), before);
LLD_CHECK_EQ(size_at(fs, "/"), 9u);
LLD_CHECK(fs.consistent());
// Up to the quota exactly is fine.
LLD_CHECK(fs.write("/docs/notes/b.txt", "xy", WriteMode::append).ok());
LLD_CHECK_EQ(size_at(fs, "/docs/notes"), 6u);
LLD_CHECK(fs.write("/docs/notes/c.txt", "").ok()); // an empty file adds nothing
}
LLD_TEST(ac_9_3_every_quota_on_the_way_to_the_root_counts) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.set_quota("/", 12).ok()); // holds 9
LLD_CHECK(fs.set_quota("/docs", 20).ok());
const auto refused = fs.write("/docs/notes/c.txt", "four");
LLD_CHECK_EQ(refused.error(), Error::quota_exceeded);
LLD_CHECK_EQ(refused.reason(), "/ holds 9 of its 12 bytes; 4 more would not fit");
LLD_CHECK(fs.write("/docs/notes/c.txt", "thr").ok());
// With two quotas over, the lowest one is named.
LLD_CHECK(fs.set_quota("/docs/notes", 7).ok());
LLD_CHECK_EQ(fs.write("/docs/notes/d", "x").reason(),
"/docs/notes holds 7 of its 7 bytes; 1 more would not fit");
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_9_4_shrinking_is_always_allowed) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.set_quota("/docs", 9).ok()); // full
LLD_CHECK(fs.write("/docs/a.txt", "ALPHA").ok()); // same size
LLD_CHECK(fs.write("/docs/a.txt", "a").ok()); // smaller
LLD_CHECK(fs.write("/docs/a.txt", "abcde").ok()); // back up to the quota
LLD_CHECK_EQ(size_at(fs, "/docs"), 9u);
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_9_5_a_quota_of_zero_allows_only_empty_files) {
FileSystem fs;
LLD_CHECK(fs.mkdir("/locked").ok());
LLD_CHECK(fs.set_quota("/locked", 0).ok());
LLD_CHECK(fs.write("/locked/empty", "").ok());
LLD_CHECK_EQ(fs.write("/locked/empty", "x", WriteMode::append).error(),
Error::quota_exceeded);
LLD_CHECK(fs.set_quota("/locked", std::nullopt).ok()); // no limit any more
LLD_CHECK(fs.write("/locked/empty", "x", WriteMode::append).ok());
}
LLD_TEST(ac_9_6_mv_checks_the_quotas_at_the_destination) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.set_quota("/tmp", 4).ok());
const std::string before = snapshot(fs);
const auto refused = fs.mv("/docs/a.txt", "/tmp/a.txt"); // 5 bytes
LLD_CHECK_EQ(refused.error(), Error::quota_exceeded);
LLD_CHECK_EQ(refused.reason(), "/tmp holds 0 of its 4 bytes; 5 more would not fit");
LLD_CHECK_EQ(snapshot(fs), before);
LLD_CHECK(fs.mv("/docs/notes", "/tmp/notes").ok()); // 4 bytes fit exactly
LLD_CHECK_EQ(size_at(fs, "/tmp"), 4u);
LLD_CHECK(fs.consistent());
}
LLD_TEST(ac_9_7_mv_inside_a_full_directory_is_allowed) {
FileSystem fs;
build(fs);
LLD_CHECK(fs.set_quota("/docs", 9).ok()); // full
LLD_CHECK(fs.set_quota("/", 9).ok()); // full
// The bytes stay inside /docs (and /), so neither total changes.
LLD_CHECK(fs.mv("/docs/a.txt", "/docs/notes/a.txt").ok());
LLD_CHECK(fs.mv("/docs/notes", "/docs/n").ok());
LLD_CHECK(fs.mv("/docs/n/a.txt", "/docs/a.txt").ok());
// Moving out of /docs to the root is allowed: / is shared, /docs shrinks.
LLD_CHECK(fs.mv("/docs/a.txt", "/a.txt").ok());
LLD_CHECK_EQ(size_at(fs, "/docs"), 4u);
// But a quota below the shared directory still counts.
LLD_CHECK(fs.set_quota("/tmp", 4).ok());
LLD_CHECK_EQ(fs.mv("/a.txt", "/tmp/a.txt").error(), Error::quota_exceeded);
LLD_CHECK(fs.consistent());
}

ac_9_7 is the test of the shared-directory rule: with /docs and / both full, moves inside /docs still work, and a move to /tmp (with its own quota of 4) is still refused. A mv that checked every directory up to the root would fail the first half; one that checked none would fail the second.

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

test_step2.cpp
// /a/x, /a/b/x, /a-c/x, /x, and /a/b/y.txt
void build_search(FileSystem& fs) {
LLD_CHECK(fs.mkdir("/a/b", Parents::create).ok());
LLD_CHECK(fs.mkdir("/a-c").ok());
for (const char* path : {"/a/x", "/a/b/x", "/a-c/x", "/x", "/a/b/y.txt"}) {
LLD_CHECK(fs.write(path, "").ok());
}
}
std::vector<std::string> found(const FileSystem& fs, std::string_view start,
std::string_view pattern) {
auto hits = fs.search(start, pattern);
return hits.ok() ? hits.value() : std::vector<std::string>{"?"};
}
LLD_TEST(ac_10_1_search_by_exact_name_is_depth_first_in_name_order) {
FileSystem fs;
build_search(fs);
// /a and all of it come before /a-c: a directory's contents are visited
// before its next sibling, even though "/a-c" sorts before "/a/b".
const std::vector<std::string> expected{"/a/b/x", "/a/x", "/a-c/x", "/x"};
LLD_CHECK_EQ(found(fs, "/", "x"), expected);
LLD_CHECK_EQ(found(fs, "/", "x"), found(fs, "/", "x")); // the same every time
}
LLD_TEST(ac_10_2_search_matches_files_and_directories_by_pattern) {
FileSystem fs;
build_search(fs);
LLD_CHECK_EQ(found(fs, "/", "*.txt"), std::vector<std::string>{"/a/b/y.txt"});
LLD_CHECK_EQ(found(fs, "/", "a*"), (std::vector<std::string>{"/a", "/a-c"}));
LLD_CHECK_EQ(found(fs, "/", "?"),
(std::vector<std::string>{"/a", "/a/b", "/a/b/x", "/a/x", "/a-c/x", "/x"}));
LLD_CHECK_EQ(found(fs, "/", "z*"), std::vector<std::string>{});
}
LLD_TEST(ac_10_3_search_looks_only_below_the_start) {
FileSystem fs;
build_search(fs);
LLD_CHECK_EQ(found(fs, "/a", "x"), (std::vector<std::string>{"/a/b/x", "/a/x"}));
LLD_CHECK_EQ(found(fs, "/a/b/..", "a"), std::vector<std::string>{}); // not /a itself
LLD_CHECK_EQ(found(fs, "/a/b", "b"), std::vector<std::string>{});
}
LLD_TEST(ac_10_4_search_refuses_bad_patterns_and_starts) {
FileSystem fs;
build_search(fs);
LLD_CHECK_EQ(fs.search("/", "").error(), Error::invalid_pattern);
LLD_CHECK_EQ(fs.search("/", "a/x").error(), Error::invalid_pattern);
LLD_CHECK_EQ(fs.search("/x", "x").error(), Error::not_a_directory);
LLD_CHECK_EQ(fs.search("/nope", "x").error(), Error::not_found);
LLD_CHECK_EQ(fs.search("a", "x").error(), Error::invalid_path);
}
LLD_TEST(ac_10_5_search_follows_moves_and_removals) {
FileSystem fs;
build_search(fs);
LLD_CHECK(fs.mv("/a/b", "/a-c/b").ok());
LLD_CHECK(fs.rm("/x").ok());
LLD_CHECK_EQ(found(fs, "/", "x"), (std::vector<std::string>{"/a/x", "/a-c/b/x", "/a-c/x"}));
}
LLD_TEST(ac_10_6_search_reaches_the_bottom_of_a_deep_tree) {
FileSystem fs;
std::string path;
for (int level = 0; level < 300; ++level) path += "/d";
LLD_CHECK(fs.mkdir(path, Parents::create).ok());
LLD_CHECK(fs.write(path + "/deep.txt", "bottom").ok());
const auto hits = found(fs, "/", "deep.txt");
LLD_CHECK_EQ(hits.size(), 1u);
LLD_CHECK(!hits.empty() && hits[0] == path + "/deep.txt");
LLD_CHECK_EQ(found(fs, "/", "d").size(), 300u);
LLD_CHECK_EQ(size_at(fs, "/"), 6u);
LLD_CHECK(fs.consistent());
}

VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).

main.cpp
// CS-17 step 2: a short scripted shell session on the in-memory file
// system, now with sizes, a quota, and search by name. Each line shows the
// command as a shell would take it, then what the FileSystem answered.
#include <iostream>
#include <string>
#include <string_view>
#include "file_system.hpp"
using namespace memfs;
namespace {
// Prints "ok", or the code and reason of a refusal.
void show(std::string_view command, const Status& status) {
std::cout << "$ " << command << '\n';
if (status.ok()) {
std::cout << " ok\n";
} else {
std::cout << " refused (" << to_string(status.error()) << "): " << status.reason() << '\n';
}
}
void show_ls(const FileSystem& fs, std::string_view path) {
std::cout << "$ ls " << path << '\n';
auto listed = fs.ls(path);
if (!listed.ok()) {
std::cout << " refused (" << to_string(listed.error()) << "): " << listed.reason() << '\n';
return;
}
for (const Entry& entry : listed.value()) {
std::cout << " " << entry.name << (entry.kind == Kind::directory ? "/" : "") << " "
<< entry.size << " bytes\n";
}
}
void show_cat(const FileSystem& fs, std::string_view path) {
std::cout << "$ cat " << path << '\n';
auto text = fs.read(path);
if (text.ok()) {
std::cout << " " << text.value() << '\n';
} else {
std::cout << " refused (" << to_string(text.error()) << "): " << text.reason() << '\n';
}
}
void show_find(const FileSystem& fs, std::string_view start, std::string_view pattern) {
std::cout << "$ find " << start << " -name '" << pattern << "'\n";
auto hits = fs.search(start, pattern);
if (!hits.ok()) {
std::cout << " refused (" << to_string(hits.error()) << "): " << hits.reason() << '\n';
return;
}
for (const std::string& path : hits.value()) std::cout << " " << path << '\n';
}
} // namespace
int main() {
FileSystem fs;
show("mkdir -p /docs/notes", fs.mkdir("/docs/notes", Parents::create));
show("mkdir /work", fs.mkdir("/work"));
show("echo plan > /docs/plan.txt", fs.write("/docs/plan.txt", "plan"));
show("echo 'call Sam' > /docs/notes/todo.txt", fs.write("/docs/notes/todo.txt", "call Sam"));
show("echo draft > /work/plan.txt", fs.write("/work/plan.txt", "draft"));
show_ls(fs, "/");
show_ls(fs, "/docs");
show("quota /docs 16", fs.set_quota("/docs", 16));
show("echo ', v2' >> /docs/plan.txt", fs.write("/docs/plan.txt", ", v2", WriteMode::append));
show("echo ' and Kim' >> /docs/notes/todo.txt",
fs.write("/docs/notes/todo.txt", " and Kim", WriteMode::append));
show("mv /work/plan.txt /docs/notes/plan.txt", fs.mv("/work/plan.txt", "/docs/notes/plan.txt"));
show("mv /docs/plan.txt /docs/notes/old-plan.txt",
fs.mv("/docs/plan.txt", "/docs/notes/old-plan.txt"));
show_ls(fs, "/docs/notes");
show_find(fs, "/", "*plan*");
show_find(fs, "/docs", "?odo.txt");
show_find(fs, "/", "a/b");
show("rm -r /docs/notes", fs.rm("/docs/notes", Recursive::yes));
show("echo 'call Sam and Kim' > /docs/todo.txt",
fs.write("/docs/todo.txt", "call Sam and Kim"));
show_cat(fs, "/docs/todo.txt");
show_ls(fs, "/");
return 0;
}
Expected output
$ mkdir -p /docs/notes
ok
$ mkdir /work
ok
$ echo plan > /docs/plan.txt
ok
$ echo 'call Sam' > /docs/notes/todo.txt
ok
$ echo draft > /work/plan.txt
ok
$ ls /
docs/ 12 bytes
work/ 5 bytes
$ ls /docs
notes/ 8 bytes
plan.txt 4 bytes
$ quota /docs 16
ok
$ echo ', v2' >> /docs/plan.txt
ok
$ echo ' and Kim' >> /docs/notes/todo.txt
refused (quota exceeded): /docs holds 16 of its 16 bytes; 8 more would not fit
$ mv /work/plan.txt /docs/notes/plan.txt
refused (quota exceeded): /docs holds 16 of its 16 bytes; 5 more would not fit
$ mv /docs/plan.txt /docs/notes/old-plan.txt
ok
$ ls /docs/notes
old-plan.txt 8 bytes
todo.txt 8 bytes
$ find / -name '*plan*'
/docs/notes/old-plan.txt
/work/plan.txt
$ find /docs -name '?odo.txt'
/docs/notes/todo.txt
$ find / -name 'a/b'
refused (invalid pattern): a pattern matches one name, so it cannot be empty or hold '/'
$ rm -r /docs/notes
ok
$ echo 'call Sam and Kim' > /docs/todo.txt
ok
$ cat /docs/todo.txt
call Sam and Kim
$ ls /
docs/ 16 bytes
work/ 5 bytes

Read the output against the rules:

  • ls / shows docs/ at 12 bytes (plan and call Sam, 4 and 8) and work/ at 5.
  • quota /docs 16 is allowed because /docs holds 12. The append of , v2 (4 bytes) fills it exactly.
  • The append to todo.txt is refused at /docs, one level above the file’s own directory.
  • The two moves are the walkthrough above: in from outside is refused, inside /docs is allowed.
  • The searches show a pattern with * on both sides, a ?, and a pattern holding /, which is refused.
  • rm -r /docs/notes gives back 16 bytes, so a new 16-byte file fits exactly, and ls / ends at 16 for /docs.

A plan for 45 minutes, using the time boxes from The design workflow:

Time What to do What to say
About 5 min Ask about relative paths, .. at the root, mv onto an existing name, rm of a full directory, and threads. “If the destination of a move exists, do we replace it, refuse, or move inside it?”
5 min Sketch the entity boxes: the file system owns the root, a directory owns its children, a child knows its parent. “Ownership points down, a plain pointer points up, so there is no cycle of owners.”
5 min Choose a variant or Composite out loud, with the reason. “Two kinds that will not grow, and many operations: a variant. More kinds later: Composite.”
10–15 min Write walk, then mv. State the check-then-change rule and INV-2. “Every check happens before the first change, so a refusal leaves nothing behind.”
5 min Trace one path with . and .., and one refused mv into itself. “The climb from the new parent meets the source, so it is refused.”
About 5 min Take a change: sizes and quotas, or search. “Cache the totals and update them on the way up; a move only checks below the shared directory.”

What is usually expected at each level

Level Usually expected
Junior Files and directories as classes or a variant; a map of children; mkdir, ls, write, read; splitting a path; a few tests.
Mid-level All of the above, plus: unique_ptr ownership with a non-owning parent; . and .. by walking the tree; mv and rm with their refusals; errors as values with a reason; a fixed ls order.
Senior All of the above, plus: no partial change on any refusal (or out of memory); an mv commit that cannot fail and cannot make a cycle; a clear Composite-or-variant argument; cached sizes with a check; quotas that cannot be got round.

These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.

How this code works: Answers to common follow-up questions
  1. Why not store each node’s full path? Because mv of a directory would have to rewrite the path of everything below it, and a missed one would be wrong in a way nothing notices. The path is found by climbing parent pointers when it is needed, which here is only for messages and traces.
  2. How would you add symbolic links? A third kind of node, holding a target path. walk would follow a link by resolving its target, with a limit on how many links it follows, because links can form loops. .. after a link becomes a real question (the link’s parent or the target’s), and rm -r must not follow links. With more kinds arriving, this is also the point to reconsider Composite.
  3. How would you make it safe for several threads? The simplest correct answer is one std::shared_mutex for the whole tree: ls, read, size, and search take it shared, everything else exclusive. Locks per directory are much harder, because mv touches two directories and, in step 2, every total up to the root, so the locks would need a fixed order. And a caller who checks with ls and then acts with write still races with other callers between the two calls; only a single call is atomic.
  4. Why does mv refuse an existing destination? The team asked for it: replacing loses work, and moving inside an existing directory makes the meaning of to depend on the tree. A replace option is the Exercise.
  5. What happens with a tree 100,000 levels deep? walk, path_of, mkdir -p, search, and consistent are loops, so they only need heap memory. Destroying the tree, by rm -r or when the FileSystem goes away, recurses once per level, and could overflow the stack. A depth limit, or a destructor that takes the tree apart with a loop, would fix it.
  6. Where would a current directory go? In the shell, not in the file system: it is a per-user setting, and the file system has no users. A shell holding a Node* would dangle after an rm -r of an ancestor, so it would hold a path instead and resolve it on each command, or the file system would need a way to say a directory is in use.
  • Not thread-safe. One thread at a time, as NFR-4 says. There are no locks, and the tsan preset builds the example but runs none of its tests, which are single-threaded.
  • One process, no persistence. Everything is lost when the FileSystem is destroyed. A real file system writes blocks to disk, and must survive a crash half way through a change, which needs a journal or copy-on-write.
  • Deep trees. Destroying a very deep tree recurses once per level, as the node header says.
  • No permissions, owners, times, or links. None of the metadata a real file system keeps.
  • Bytes, not text. A name is any bytes except / and the zero byte, compared byte by byte. There is no Unicode normalisation, so two names that look the same can be different names, and ls sorts by bytes, not for people.
  • Whole files in memory. read copies the file, and write replaces or extends it. There are no file handles, no reading part of a file, and no limit on a file’s size other than memory.
  • No out-of-memory test. The all-or-nothing claim for a std::bad_alloc comes from the order of the code and the standard library’s guarantees; no test injects a failed allocation.
  • Quotas count file bytes only. Directories and names are free, which a real system would not allow, and there is one quota per directory, not per user.

FR-8 to FR-10 are the change: FR-8 sizes (UC-8), FR-9 quotas (UC-9), and FR-10 search by name (UC-10, UC-11).

Requirement Design element Code Tests Status
FR-1 paths split_path, walk, trace, is_valid_name step 1 path.*, file_system.cpp ac_1_1_… to ac_1_8_… Tested
FR-2 mkdir mkdir, target, the chain built off the tree step 1 file_system.cpp ac_2_1_… to ac_2_6_… Tested
FR-3 ls ls, the sorted Children map step 1 node.hpp, file_system.cpp ac_3_1_… to ac_3_3_… Tested
FR-4 write and read write, read, WriteMode step 1 file_system.cpp ac_4_1_… to ac_4_5_… Tested
FR-5 mv mv: the checks, the climb, extract and insert step 1 file_system.cpp ac_5_1_… to ac_5_6_… Tested
FR-6 rm rm, Recursive step 1 file_system.cpp ac_6_1_… to ac_6_4_… Tested
FR-7 refusals Error, Failure, Result; check before change step 1 result.hpp, every command ac_7_1_…, every snapshot comparison Tested
NFR-1 clear ownership std::unique_ptr children, Node* parent step 1 node.hpp ac_7_2_…, consistent; asan-ubsan run Tested
NFR-2 all or nothing check, build, change; node handles step 1 file_system.cpp refusals only; no out-of-memory test Partly tested
NFR-3 a fixed order std::map order; search’s stack step 1 node.hpp, step 2 search ac_3_1_…, ac_10_1_… Tested
NFR-4 not thread-safe documented in the example notes and on this page none none: a statement, not a behaviour Stated
NFR-5 testable on its own trace, consistent step 1 file_system.* ac_1_8_…, most tests Tested
FR-8 sizes Directory::bytes, add_bytes, remove_bytes, size step 2 node.hpp, file_system.cpp ac_8_1_… to ac_8_5_… Tested
FR-9 quotas quota, set_quota, check_room, the shared directory step 2 file_system.cpp ac_9_1_… to ac_9_7_… Tested
FR-10 search by name search, matches step 2 file_system.cpp, pattern.* ac_10_1_… to ac_10_6_…, ac_11_1_… Tested

Exercise: Let mv replace a file when asked

The team changes its mind about one case. A tool that saves a file by writing /docs/a.txt.new and then moving it onto /docs/a.txt needs mv to replace the old file. Add a Replace flag to mv, starting from step 2, so that with Replace::yes a file may replace a file. Everything else stays refused.

  1. Which cases must still be refused with the flag on, and why?
  2. How does the commit step change, and can it still not fail?
  3. What do the quota check and the totals become?
  4. Which tests would you add?
Show the explained answer
  1. Still refused. A directory as the destination (replacing it would delete everything below it, which is rm -r by another name), and a directory as the source onto a file (the shell does not allow it either, and the old file would vanish under a new directory). The source and the destination being the same entry (mv /docs/a.txt /docs/./a.txt) must be caught before the commit: the code below would otherwise put the file in place of itself and then destroy it. The check is “the destination entry’s node is the source node”, either refused or done as nothing. Everything from step 1 (the root, missing paths, into itself) is unchanged.

  2. The commit. The destination’s map entry already exists, so the moved node goes into that entry, and the old file comes out of it. Nothing allocates, so nothing can fail:

    IllustrativeA fragment for explanation; not compiled on its own.

    // Illustrative: the commit of mv with Replace::yes, when
    // `to_name` names an existing file in `to_children`. Every check, the
    // quota check included, has already passed.
    auto existing = to_children.find(to_name); // the file to be replaced
    // Unlink the source. Iterators to other map entries, such as
    // `existing`, stay valid, even when both are in the same directory.
    auto handle = from_children.extract(entry);
    node->parent = to_parent; // the back pointer, as in step 1
    // Put the moved node into the existing entry and take the old file
    // out. std::exchange returns the old unique_ptr; moving pointers
    // does not allocate.
    std::unique_ptr<Node> old = std::exchange(existing->second, std::move(handle.mapped()));
    // `handle` now owns an empty pointer and only frees its map node.
    // `old` destroys the replaced file at the end of the scope.
  3. Quotas and totals. Below the shared directory, the destination side gains the moved bytes and loses the replaced file’s bytes. So the check is check_room(*to_parent, moved - old_size, shared), and only when moved > old_size: a replacement by a smaller file cannot break a quota. After the commit, take the moved bytes out above the old place and the replaced bytes out above the new place, then add the moved bytes above the new place: remove_bytes(*from_parent, moved), remove_bytes(*to_parent, old_size), add_bytes(*to_parent, moved). Subtracting before adding keeps every total from going below zero on the way.

  4. Tests. A file replaces a file, and read gives the new bytes; the flag does not let a file replace a directory, or a directory replace a file, and nothing changes; the same entry is caught; a replacement by a larger file over a full quota is refused, and by a smaller one is allowed; and size and consistent are right after each. Without the flag, AC-5.5 still holds.

This answer was checked in a scratch copy of step 2 (not part of the example): mv with a Replace flag built as above, refusing the same entry with already_exists, and one new test for the cases in point 4. With g++ 11.4 and clang++ 14, both with AddressSanitizer and UndefinedBehaviorSanitizer, the new test and the 53 existing step 2 tests passed.

  • A variant of the node kinds fits when the kinds are few and fixed and the operations keep growing; Composite fits when the kinds keep growing.
  • Own downwards, point upwards. A directory owns its children by std::unique_ptr; a child knows its parent by a plain pointer that owns nothing. No ownership cycles, and rm -r is one erase.
  • Store each fact once. The name is the map key, the path is climbed, so a rename or a move cannot leave copies that disagree.
  • Resolve .. against the tree, one part at a time, never by cutting text.
  • Check everything, build, then change. A refusal leaves nothing behind, and the change itself is made of steps that cannot fail, like extract and insert of a node handle.
  • Cache what is asked for often, update it on the way up, and keep a slow check (consistent) that recomputes it for the tests.
  • A move changes no total above the shared directory, so it is checked only below it.
  • Choose a plain loop over Visitor when there is nothing for the pattern to organise, and an explicit stack when depth must not reach the call stack.