Case study: In-memory file system
What you will learn on this page
Section titled “What you will learn on this page”- 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::mapofstd::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.txtis 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
mvmoves 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.
The request
Section titled “The request”“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.
Step 1 of the framework: Requirements
Section titled “Step 1 of the framework: Requirements”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.
Clarifying questions
Section titled “Clarifying questions”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), andrm(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):
lssorts names in byte order, soBcomes beforeaand10before9. 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. lsof 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.
Requirements
Section titled “Requirements”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.
writecreates a file, replaces its bytes, or appends to them; its parent must exist.readreturns 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.
Use cases and acceptance criteria
Section titled “Use cases and acceptance criteria”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.txtreadsalpha. - AC-1.3
.stays and..goes to the parent:/docs/./notes/../a.txtreadsalpha, andls /docs/..listsdocs/ 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/..isnot_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/.., andmvfrom or to a path ending in.are refused, and the tree does not change. - AC-1.8
traceshows each part read and where it led, or the reason it stopped.
UC-2 Make a directory.
- AC-2.1
mkdir /docscreates an empty directory. - AC-2.2 A name that is taken, by a directory or a file, is refused
(
already_exists), and so ismkdir /. - AC-2.3 Without parents, a missing parent is refused (
not_found, “‘x’ does not exist in /”), and a file as the parent isnot_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 isalready_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
lsis sorted by name in byte order:10 9 B a a-c b c/. - AC-3.2
lsof a file lists that file;lsof an empty directory lists nothing. - AC-3.3
lsof 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
writecreates a file, andreadreturns its bytes, also for an empty file. - AC-4.2
writereplaces the bytes, and append adds to them. - AC-4.3 Append to a missing file creates it.
- AC-4.4
writeto a directory (or/) isis_a_directory; a missing parent isnot_found; a file as the parent isnot_a_directory. Nothing changes. - AC-4.5
readof a directory isis_a_directory; of a missing file,not_found.
UC-5 Move or rename.
- AC-5.1
mvrenames a file or a directory in place. - AC-5.2
mvmoves a directory with everything below it, and..from it now leads to its new parent. - AC-5.3
mvmoves 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
mvnever replaces: a file, a directory, the source itself, or/as the destination isalready_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
rmremoves 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//) isis_root; a missing entry isnot_found.
UC-7 The whole tree.
- AC-7.1 Every refusal has a code other than
noneand a reason that is not empty; a command that worked hasnoneand no reason. - AC-7.2 After a mixed run of
mkdir,write,mv, andrm, the tree is consistent and holds exactly what it should.
Invariants
Section titled “Invariants”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 ofFileSystem. Kept by the types: aunique_ptrcannot be copied, so a node cannot end up in two maps. - INV-2 Parent pointers are right. Every child’s
parentpoints at the directory whose map holds it, and only the root’s isnullptr. Kept bymkdirandwrite, which build each node with its parent, and bymv, which sets it. Checked byconsistent. - 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
targetandmkdir, which check withis_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
FileSystemclass: 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
Nodetype, and what differs (children or bytes) is astd::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::stringin aFile. - Command is a member function of
FileSystem. Refusal and reason are aFailure(anErrorcode and a sentence) inside aResult.
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)"| NRead 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.
Step 3 of the framework: Class design
Section titled “Step 3 of the framework: Class design”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.
What each class must remember
Section titled “What each class must remember”| 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.
What each class must do
Section titled “What each class must do”| 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.)
Class outlines
Section titled “Class outlines”struct Node
one type for files and directories
Data members
Node* parent = nullptr;public; non-owning; nullptr only for the rootstd::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 testsResult<Reached> walk(const std::vector<std::string>& parts, OnMissing missing, std::vector<Step>* trace) const;privateResult<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 workedstd::string reason() const;empty when it workedconst T& value() const&;T value() &&;a temporary hands its value over
struct Failure
Data members
Error error;publicstd::string reason;public
enum class Error
Values
noneinvalid_pathnot_foundnot_a_directoryis_a_directoryalready_existsnot_emptyinto_itselfis_root
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.
The node
Section titled “The node”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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.
Errors and results
Section titled “Errors and results”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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).
// 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
- One of two things. A
Result<std::string>holds astd::variant<std::string, Failure>: either the bytes thatreadfound, or the reason it did not.ok()asks which one is there. - Two ways to read a refusal.
error()gives the code (a test or a shell canswitchon it), andreason()the sentence for a person. Both are safe to call on a success: they giveError::noneand an empty string. - Why
value()has three versions. The&,const&, and&&after the parentheses choose a version by what theResultis. For a namedResult, the first two lend a reference to the value inside. For a temporary, such as the onefs.read("/a.txt")returns when it is used straight away,&&is chosen, and it moves the value out and returns it by value. - What that prevents. Without the
&&version,const std::string& text = fs.read("/a.txt").value();would bindtextto a string inside a temporary that is destroyed at the end of the line, leaving a dangling reference. With it,value()returns astd::stringby value, and binding aconst&to that returned temporary extends its life to matchtext. The same idea is whyreason()returns a copy. [[nodiscard]]on the class. Every function that returns aResultis then[[nodiscard]]by itself: writingfs.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.
The file system
Section titled “The file system”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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>.
Step 4 of the framework: Implementation
Section titled “Step 4 of the framework: Implementation”Every command has the same shape, and it is worth seeing once before the details:
- Split the path into names (
split_path). A bad path stops here. - Walk the tree to the directory the command works in (
walk, ortargetfor a change). A missing or wrong node stops here. - Check every other rule of the command (a name is free, a directory is empty, a directory is not moving into itself).
- Build anything that needs memory (a new node, a new name).
- 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.
Splitting a path
Section titled “Splitting a path”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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.
Walking the tree
Section titled “Walking the tree”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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 |
- 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 everyat beforeis one. The last node reached is a file, which is fine: rule 1 only applies when there is another part to read. .and..are rules, not names. They are never looked up in the map, so a file called..cannot exist (andis_valid_namerefuses to make one)...uses the parent pointer. Passes 4 and 5 followat->parent. That pointer is why aNodehas one.- 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. - 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.
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.
The last part: target
Section titled “The last part: target”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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.
mkdir and mkdir -p
Section titled “mkdir and mkdir -p”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
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.
-
Walk as far as the tree goes.
walkwithOnMissing::stopfindsdocs, then does not findnotes, and returnsReached{/docs, 1}: it stopped at/docsafter using one part. -
Everything from
usedon is new.all[1]isnotesandall[2]is2026. Both must be plain names: a directory that does not exist yet has no.or..inside it, somkdir -p /new/./yis refused (AC-2.6), before anything is built. -
Build the chain off the tree.
topis a new directorynoteswhose parent pointer already names/docs. The loop makes2026withbottom(notes) as its parent, and puts it innotes’s map. Nothing in the tree has changed: the chain hangs fromtop, a localstd::unique_ptr.Variable Points at In the tree? parent/docsyes topthe new notesnot yet bottomthe new 2026, innotesnot yet -
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 andtopstill frees the chain; if it works, the chain is in the tree. There is no moment at which/docs/notesexists without2026. -
Node* next = child.get()is read beforestd::move(child), because after the movechildis 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).
write and read
Section titled “write and read”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
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).
// 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.
- Both paths split. Neither is the root.
targeton the source gives/docsandnotes. The entry exists;nodeis thenotesnode.targeton the destination gives/andarchive. The root has noarchive, so the name is free.- The climb.
upstarts at the new parent,/. It is notnotes, and its parent isnullptr, so the climb ends:notesis not moving into itself. - Commit.
extractunlinks the map entry and hands it over as a node handle; theNodeobject does not move in memory.handle.key()is renamed toarchive(moving the string thattargetbuilt, so no allocation),node->parentis set to the root, andinsertputs the handle into the root’s map. Inserting a node handle reuses its memory, so it cannot run out of memory. The child2026still points at the samenotesnode, now calledarchive, 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).
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:
- The path must split, and
rm /(orrm //, which splits to the same nothing) isis_root. - The last part must be a real name, and its directory must exist
(
target). - The entry must exist (
not_found). - A directory with children needs
Recursive::yes(not_empty). The flag on a file or an empty directory is harmless. - Then one
erase. Destroying the entry’sunique_ptrdestroys 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.
Where each rule lives
Section titled “Where each rule lives”| 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 |
Verification trace
Section titled “Verification trace”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.
Building it step by step
Section titled “Building it step by step”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.
The step 1 demo
Section titled “The step 1 demo”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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;}$ 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).
// 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, /tmpvoid 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).
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).
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.
Step 5 of the framework: Extensibility
Section titled “Step 5 of the framework: Extensibility”The last step takes a change to the requirements and shows which parts of the design move and which stay.
The change request
Section titled “The change request”“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. |
Use cases for the change
Section titled “Use cases for the change”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 (
/docsis 9 foralphaandbeta), and an empty directory is 0. New directories add nothing. - AC-8.2
writeand append keep every total right, both when a file grows and when it shrinks. - AC-8.3
mvcarries the bytes to the new place; a rename changes no total. - AC-8.4
rmtakes the bytes away. - AC-8.5
lsshows 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
mvchecks the quotas at the destination, and a refusedmvchanges nothing. - AC-9.7
mvinside 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
/isinvalid_pattern; a file as the start isnot_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
bytesequals the sum of the files below it. Kept byadd_bytesandremove_bytes, called bywrite,mv, andrmafter their change. Checked byconsistent. - INV-7 No directory is over its quota. Kept by
set_quota, which refuses a quota below the total, and bycheck_room, called before every change that adds bytes. Checked byconsistent.
What moved
Section titled “What moved”| 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 1std::size_t bytes = 0;public; cached: all file bytes belowstd::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;publicKind kind;publicstd::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.cppvoid add_bytes(Node& dir, std::size_t amount) noexcept;file_system.cppvoid remove_bytes(Node& dir, std::size_t amount) noexcept;file_system.cppbool matches(std::string_view name, std::string_view pattern) noexcept;pattern.hpp
Sizes, cached
Section titled “Sizes, cached”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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.
Quotas
Section titled “Quotas”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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.
-
The old parent is
/work, the new parent/docs/notes. -
Find the shared directory. Start at
/docs/notes: is it/workor above it? No./docs? No./? Yes. Sosharedis the root. -
Check up to, not including, the root.
Directory bytesquota5 more fit? /docs/notes8 none yes /docs16 16 no: 5 > 0 -
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.
- The old parent is
/docs, the new parent/docs/notes. - Start at
/docs/notes: is it/docsor above it? No. Its parent/docs: yes. Sosharedis/docs. - Only
/docs/notesis checked. It has no quota, so the move is allowed, although/docsis full: the bytes stay inside it. - 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.
Checking the totals without recursion
Section titled “Checking the totals without recursion”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
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.
-
First pass: list every node, parents first.
pendingis a stack. The root is popped and listed, and its childrendocsandtmppushed in name order, sotmpis on top and popped next. Thendocs, which pushesa.txtandnotes; thennotes, which pushesb.txt; thenb.txt, thena.txt.orderends 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. -
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.txt5 (a file) /docs: 5/docs/notes/b.txt4 (a file) /docs/notes: 4/docs/notessumsgives 4bytesis 4: ok/docs: 9/docssumsgives 9bytesis 9: ok/: 9/tmpsumsgives 0bytesis 0: ok/: 9/sumsgives 9bytesis 9: ok(no parent) -
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.
Search by name
Section titled “Search by name”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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).
// 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.
-
Start.
push_childrenpushes the root’s children in reverse name order,/x,/a-c,/a, so the smallest name,/a, is on top. -
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 /ano /a/x,/a/b/x,/a-c,/a/x,/a/b/a/bno /a/b/y.txt,/a/b/x/x,/a-c,/a/x,/a/b/y.txt,/a/b/x/a/b/xyes (a file) /x,/a-c,/a/x,/a/b/y.txt/a/b/y.txtno (a file) /x,/a-c,/a/x/a/xyes (a file) /x,/a-c/a-cno /a-c/x/x,/a-c/x/a-c/xyes (a file) /x/xyes (a file) empty -
The answer is
/a/b/x,/a/x,/a-c/x,/x, the order the test expects. All of/acomes before/a-c, even though the string/a-csorts before/a/b, because a directory’s contents are visited before its next sibling. -
Pending::nameis astd::string_viewof the key in the parent’s map. It stays valid becausesearchisconstand nothing changes the tree while it runs. -
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.
Step 2 tests
Section titled “Step 2 tests”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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).
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).
// /a/x, /a/b/x, /a-c/x, /x, and /a/b/y.txtvoid 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());}The step 2 demo
Section titled “The step 2 demo”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// 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;}$ 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 bytesRead the output against the rules:
ls /showsdocs/at 12 bytes (planandcall Sam, 4 and 8) andwork/at 5.quota /docs 16is allowed because/docsholds 12. The append of, v2(4 bytes) fills it exactly.- The append to
todo.txtis refused at/docs, one level above the file’s own directory. - The two moves are the walkthrough above: in from outside is
refused, inside
/docsis allowed. - The searches show a pattern with
*on both sides, a?, and a pattern holding/, which is refused. rm -r /docs/notesgives back 16 bytes, so a new 16-byte file fits exactly, andls /ends at 16 for/docs.
Presenting it in an interview
Section titled “Presenting it in an interview”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.
Questions an interviewer might ask
Section titled “Questions an interviewer might ask”How this code works: Answers to common follow-up questions
- Why not store each node’s full path? Because
mvof 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. - How would you add symbolic links? A third kind of node, holding
a target path.
walkwould 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), andrm -rmust not follow links. With more kinds arriving, this is also the point to reconsider Composite. - How would you make it safe for several threads? The simplest
correct answer is one
std::shared_mutexfor the whole tree:ls,read,size, andsearchtake it shared, everything else exclusive. Locks per directory are much harder, becausemvtouches 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 withlsand then acts withwritestill races with other callers between the two calls; only a single call is atomic. - Why does
mvrefuse an existing destination? The team asked for it: replacing loses work, and moving inside an existing directory makes the meaning oftodepend on the tree. A replace option is the Exercise. - What happens with a tree 100,000 levels deep?
walk,path_of,mkdir -p,search, andconsistentare loops, so they only need heap memory. Destroying the tree, byrm -ror when theFileSystemgoes 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. - 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 anrm -rof 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.
Production limitations
Section titled “Production limitations”- 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
FileSystemis 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, andlssorts by bytes, not for people. - Whole files in memory.
readcopies the file, andwritereplaces 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_alloccomes 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.
Traceability
Section titled “Traceability”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
Section titled “Exercise”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.
- Which cases must still be refused with the flag on, and why?
- How does the commit step change, and can it still not fail?
- What do the quota check and the totals become?
- Which tests would you add?
Show the explained answer
-
Still refused. A directory as the destination (replacing it would delete everything below it, which is
rm -rby 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. -
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. -
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 whenmoved > 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. -
Tests. A file replaces a file, and
readgives 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; andsizeandconsistentare 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.
Summary
Section titled “Summary”- 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, andrm -ris oneerase. - 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
extractandinsertof 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.