Playground
gnomod.toml
module = "gno.land/p/nym-moultest123/x/plan9/memfs/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186409 max_deposit = "8000000ugnot"
memfs.gno
// Package memfs is a RAM file server: Plan 9's ramfs, in a realm's heap.
//
// It is the reference implementation of gno.land/p/nym-moultest123/x/plan9/ninep's File
// and Mutable, and the tree a namespace server hands out as a user's private
// root. Children live in an avl.Tree, so a directory listing is ordered by
// name and therefore identical on every validating node; a map would make
// Render a consensus bug.
//
// Mutable is IN-REALM ONLY. A non-crossing method runs in the caller's frame,
// so a foreign realm calling Create or Write here would be mutating objects it
// does not own. Reads (the ninep.File half) are safe from anywhere, which is
// what makes a memfs tree mountable into somebody else's namespace.
//
// The caller supplies the clock (a block height) on every mutation rather than
// the tree reading chain state itself, so the same tree is exercisable in a
// plain unit test.
//
// NOTICE. Plan 9 from Bell Labs is the work of the Computing Science Research
// Center at Bell Labs; the name and the marks are theirs, and the copyright is
// held by the Plan 9 Foundation (https://p9f.org). This package is not
// affiliated with, endorsed by, or sponsored by them, and contains no Plan 9
// code: it borrows the vocabulary so that the design reads without a glossary,
// and it is an homage, asking what that ecosystem's spirit looks like on a
// chain. Full attribution: NOTICE.md at the root of moul/gno-contracts.
package memfs
import (
"strings"
"gno.land/p/nt/avl/v0"
ninep "gno.land/p/nym-moultest123/x/plan9/ninep/v0"
)
// FS is a mutable in-memory file tree.
type FS struct {
root *node
next uint64 // qid path allocator, unique for this server's lifetime
uid string
}
type node struct {
fs *FS
name string
perm ninep.Perm
qid ninep.Qid
data string
children *avl.Tree // name -> *node; nil for a plain file
mtime int64
uid string
gid string
muid string
}
// New returns an empty file server owned by uid, with its root created at
// block height now.
func New(uid string, now int64) *FS {
fs := &FS{uid: uid}
fs.root = fs.newNode("/", ninep.DirPerm, now)
return fs
}
// Root returns the server's root directory.
func (fs *FS) Root() ninep.File { return fs.root }
// RootMutable returns the root as a Mutable. Only call it from the realm that
// owns this FS.
func (fs *FS) RootMutable() ninep.Mutable { return fs.root }
// Uid returns the owner this server stamps on new files.
func (fs *FS) Uid() string { return fs.uid }
func (fs *FS) newNode(name string, perm ninep.Perm, now int64) *node {
fs.next++
qt := ninep.QTFILE
var kids *avl.Tree
if perm.IsDir() {
qt = ninep.QTDIR
kids = avl.NewTree()
}
return &node{
fs: fs,
name: name,
perm: perm,
qid: ninep.Qid{Type: qt, Version: 0, Path: fs.next},
children: kids,
mtime: now,
uid: fs.uid,
gid: fs.uid,
muid: fs.uid,
}
}
// Stat implements ninep.File.
func (n *node) Stat() ninep.Stat {
length := int64(len(n.data))
if n.perm.IsDir() {
length = 0 // 9P reports zero for a directory
}
return ninep.Stat{
Qid: n.qid,
Mode: n.perm,
Mtime: n.mtime,
Length: length,
Name: n.name,
Uid: n.uid,
Gid: n.gid,
Muid: n.muid,
}
}
// Walk implements ninep.File.
func (n *node) Walk(name string) (ninep.File, error) {
if !n.perm.IsDir() {
return nil, ninep.ErrNotDir
}
if !ninep.ValidName(name) {
return nil, ninep.ErrBadName
}
v := n.children.Get(name) // avl.Get returns ONE value in gno
if v == nil {
return nil, ninep.ErrNotExist
}
return v.(*node), nil
}
// Read implements ninep.File.
func (n *node) Read(off, count int64) (string, error) {
if n.perm.IsDir() {
return "", ninep.ErrIsDir
}
return ninep.Slice(n.data, off, count), nil
}
// ReadDir implements ninep.File.
func (n *node) ReadDir() ([]ninep.Stat, error) {
if !n.perm.IsDir() {
return nil, ninep.ErrNotDir
}
out := []ninep.Stat{}
n.children.Iterate("", "", func(_ string, v any) bool {
out = append(out, v.(*node).Stat())
return false
})
return out, nil
}
// Create implements ninep.Mutable.
func (n *node) Create(name string, perm ninep.Perm, now int64) (ninep.File, error) {
if !n.perm.IsDir() {
return nil, ninep.ErrNotDir
}
if !ninep.ValidName(name) {
return nil, ninep.ErrBadName
}
if n.children.Has(name) {
return nil, ninep.ErrExist
}
child := n.fs.newNode(name, perm, now)
n.children.Set(name, child)
n.touch(now)
return child, nil
}
// Remove implements ninep.Mutable. A non-empty directory is refused, as in
// Plan 9.
func (n *node) Remove(name string) error {
if !n.perm.IsDir() {
return ninep.ErrNotDir
}
v := n.children.Get(name)
if v == nil {
return ninep.ErrNotExist
}
child := v.(*node)
if child.perm.IsDir() && child.children.Size() > 0 {
return ninep.ErrNotEmpty
}
n.children.Remove(name)
n.touch(n.mtime)
return nil
}
// Write implements ninep.Mutable. Writing past the end extends the file with
// NUL bytes, as a 9P server does.
func (n *node) Write(off int64, data string, now int64) (int64, error) {
if n.perm.IsDir() {
return 0, ninep.ErrIsDir
}
if off < 0 {
off = 0
}
if n.perm&ninep.DMAPPEND != 0 {
off = int64(len(n.data))
}
cur := n.data
if off > int64(len(cur)) {
cur += strings.Repeat("\x00", int(off)-len(cur))
}
end := off + int64(len(data))
tail := ""
if end < int64(len(cur)) {
tail = cur[end:]
}
n.data = cur[:off] + data + tail
n.touch(now)
return int64(len(data)), nil
}
// Truncate implements ninep.Mutable.
func (n *node) Truncate(size int64, now int64) error {
if n.perm.IsDir() {
return ninep.ErrIsDir
}
if size < 0 {
size = 0
}
switch {
case size < int64(len(n.data)):
n.data = n.data[:size]
case size > int64(len(n.data)):
n.data += strings.Repeat("\x00", int(size)-len(n.data))
}
n.touch(now)
return nil
}
// touch bumps the qid version and the mtime. A client that kept a qid can tell
// the file changed without reading it, which is the whole point of Qid.Version.
func (n *node) touch(now int64) {
n.qid.Version++
n.mtime = now
n.muid = n.fs.uid
}
// MkdirAll creates p and every missing parent, and returns the leaf. An
// existing directory is not an error; an existing plain file on the path is.
func (fs *FS) MkdirAll(p string, now int64) (ninep.File, error) {
cur := fs.root
for _, e := range ninep.Elems(p) {
v := cur.children.Get(e)
if v == nil {
f, err := cur.Create(e, ninep.DirPerm, now)
if err != nil {
return nil, err
}
cur = f.(*node)
continue
}
cur = v.(*node)
if !cur.perm.IsDir() {
return nil, ninep.ErrNotDir
}
}
return cur, nil
}
// WriteFile creates or replaces the file at p, creating parent directories as
// needed. It is the seeding helper a realm wants at init.
func (fs *FS) WriteFile(p, data string, now int64) error {
dir, err := fs.MkdirAll(ninep.Dir(p), now)
if err != nil {
return err
}
name := ninep.Base(p)
d := dir.(*node)
v := d.children.Get(name)
if v == nil {
f, err := d.Create(name, ninep.FilePerm, now)
if err != nil {
return err
}
_, err = f.(*node).Write(0, data, now)
return err
}
target := v.(*node)
if err := target.Truncate(0, now); err != nil {
return err
}
_, err = target.Write(0, data, now)
return err
}
memfs_test.gno
package memfs
import (
"testing"
ninep "gno.land/p/nym-moultest123/x/plan9/ninep/v0"
)
func TestRootStat(t *testing.T) {
fs := New("glenda", 100)
s := fs.Root().Stat()
if s.Name != "/" {
t.Errorf("root name: got %q", s.Name)
}
if !s.IsDir() {
t.Error("root should be a directory")
}
if s.Length != 0 {
t.Errorf("a directory reports length 0 in 9P, got %d", s.Length)
}
if s.Uid != "glenda" || s.Gid != "glenda" {
t.Errorf("owner: got %q/%q", s.Uid, s.Gid)
}
if s.Mtime != 100 {
t.Errorf("mtime: got %d, want 100", s.Mtime)
}
}
func TestCreateWalkRead(t *testing.T) {
fs := New("glenda", 1)
root := fs.RootMutable()
f, err := root.Create("greeting", ninep.FilePerm, 2)
if err != nil {
t.Fatalf("create: %v", err)
}
m := f.(ninep.Mutable)
n, err := m.Write(0, "hello world", 3)
if err != nil {
t.Fatalf("write: %v", err)
}
if n != 11 {
t.Errorf("wrote %d bytes, want 11", n)
}
got, err := root.Walk("greeting")
if err != nil {
t.Fatalf("walk: %v", err)
}
data, err := ninep.ReadAll(got)
if err != nil {
t.Fatalf("read: %v", err)
}
if data != "hello world" {
t.Errorf("read back %q", data)
}
if l := got.Stat().Length; l != 11 {
t.Errorf("length %d, want 11", l)
}
}
func TestWalkErrors(t *testing.T) {
fs := New("glenda", 1)
root := fs.RootMutable()
root.Create("file", ninep.FilePerm, 1)
if _, err := root.Walk("absent"); err != ninep.ErrNotExist {
t.Errorf("missing name: got %v, want ErrNotExist", err)
}
if _, err := root.Walk("a/b"); err != ninep.ErrBadName {
t.Errorf("slash in name: got %v, want ErrBadName", err)
}
f, _ := root.Walk("file")
if _, err := f.Walk("x"); err != ninep.ErrNotDir {
t.Errorf("walk through a file: got %v, want ErrNotDir", err)
}
if _, err := f.ReadDir(); err != ninep.ErrNotDir {
t.Errorf("readdir of a file: got %v, want ErrNotDir", err)
}
if _, err := root.Read(0, -1); err != ninep.ErrIsDir {
t.Errorf("read of a directory: got %v, want ErrIsDir", err)
}
}
func TestReadDirIsOrdered(t *testing.T) {
fs := New("glenda", 1)
root := fs.RootMutable()
for _, name := range []string{"zulu", "alpha", "mike", "bravo"} {
if _, err := root.Create(name, ninep.FilePerm, 1); err != nil {
t.Fatalf("create %s: %v", name, err)
}
}
ents, err := root.ReadDir()
if err != nil {
t.Fatalf("readdir: %v", err)
}
want := []string{"alpha", "bravo", "mike", "zulu"}
if len(ents) != len(want) {
t.Fatalf("got %d entries, want %d", len(ents), len(want))
}
for i, w := range want {
if ents[i].Name != w {
t.Errorf("entry %d: got %q, want %q", i, ents[i].Name, w)
}
}
}
func TestCreateDuplicate(t *testing.T) {
fs := New("glenda", 1)
root := fs.RootMutable()
root.Create("x", ninep.FilePerm, 1)
if _, err := root.Create("x", ninep.FilePerm, 1); err != ninep.ErrExist {
t.Errorf("got %v, want ErrExist", err)
}
if _, err := root.Create("", ninep.FilePerm, 1); err != ninep.ErrBadName {
t.Errorf("empty name: got %v, want ErrBadName", err)
}
if _, err := root.Create("..", ninep.FilePerm, 1); err != ninep.ErrBadName {
t.Errorf("dotdot: got %v, want ErrBadName", err)
}
}
func TestRemove(t *testing.T) {
fs := New("glenda", 1)
root := fs.RootMutable()
root.Create("file", ninep.FilePerm, 1)
d, _ := root.Create("dir", ninep.DirPerm, 1)
d.(ninep.Mutable).Create("inner", ninep.FilePerm, 1)
if err := root.Remove("absent"); err != ninep.ErrNotExist {
t.Errorf("remove missing: got %v", err)
}
if err := root.Remove("dir"); err != ninep.ErrNotEmpty {
t.Errorf("remove non-empty dir: got %v, want ErrNotEmpty", err)
}
if err := d.(ninep.Mutable).Remove("inner"); err != nil {
t.Fatalf("remove inner: %v", err)
}
if err := root.Remove("dir"); err != nil {
t.Fatalf("remove emptied dir: %v", err)
}
if err := root.Remove("file"); err != nil {
t.Fatalf("remove file: %v", err)
}
ents, _ := root.ReadDir()
if len(ents) != 0 {
t.Errorf("root should be empty, has %d entries", len(ents))
}
}
func TestWriteOffsets(t *testing.T) {
tests := []struct {
name string
start string
off int64
data string
want string
}{
{"append at end", "abc", 3, "def", "abcdef"},
{"overwrite middle", "abcdef", 2, "XY", "abXYef"},
{"overwrite past end", "abc", 2, "XYZ", "abXYZ"},
{"from zero", "abcdef", 0, "ZZ", "ZZcdef"},
{"gap is nul filled", "ab", 4, "Z", "ab\x00\x00Z"},
{"negative offset clamps", "abc", -2, "Z", "Zbc"},
}
for _, tt := range tests {
fs := New("glenda", 1)
root := fs.RootMutable()
f, _ := root.Create("f", ninep.FilePerm, 1)
m := f.(ninep.Mutable)
m.Write(0, tt.start, 1)
m.Write(tt.off, tt.data, 2)
got, _ := ninep.ReadAll(f)
if got != tt.want {
t.Errorf("%s: got %q, want %q", tt.name, got, tt.want)
}
}
}
func TestAppendOnlyIgnoresOffset(t *testing.T) {
fs := New("glenda", 1)
root := fs.RootMutable()
f, _ := root.Create("log", ninep.DMAPPEND|0644, 1)
m := f.(ninep.Mutable)
m.Write(0, "one\n", 1)
m.Write(0, "two\n", 2) // offset 0, but append-only pins it to the end
got, _ := ninep.ReadAll(f)
if got != "one\ntwo\n" {
t.Errorf("got %q", got)
}
}
func TestTruncate(t *testing.T) {
fs := New("glenda", 1)
root := fs.RootMutable()
f, _ := root.Create("f", ninep.FilePerm, 1)
m := f.(ninep.Mutable)
m.Write(0, "abcdef", 1)
m.Truncate(3, 2)
if got, _ := ninep.ReadAll(f); got != "abc" {
t.Errorf("shrink: got %q", got)
}
m.Truncate(5, 3)
if got, _ := ninep.ReadAll(f); got != "abc\x00\x00" {
t.Errorf("grow: got %q", got)
}
m.Truncate(0, 4)
if got, _ := ninep.ReadAll(f); got != "" {
t.Errorf("zero: got %q", got)
}
}
func TestQidVersionAndPath(t *testing.T) {
fs := New("glenda", 1)
root := fs.RootMutable()
a, _ := root.Create("a", ninep.FilePerm, 1)
b, _ := root.Create("b", ninep.FilePerm, 1)
if a.Stat().Qid.Path == b.Stat().Qid.Path {
t.Error("two files share a qid path")
}
v0 := a.Stat().Qid.Version
a.(ninep.Mutable).Write(0, "x", 2)
if a.Stat().Qid.Version != v0+1 {
t.Errorf("version did not advance on write: %d -> %d", v0, a.Stat().Qid.Version)
}
if a.Stat().Mtime != 2 {
t.Errorf("mtime: got %d, want 2", a.Stat().Mtime)
}
}
func TestMkdirAllAndWriteFile(t *testing.T) {
fs := New("glenda", 1)
if _, err := fs.MkdirAll("/usr/glenda/lib", 1); err != nil {
t.Fatalf("mkdirall: %v", err)
}
// idempotent
if _, err := fs.MkdirAll("/usr/glenda", 1); err != nil {
t.Fatalf("mkdirall again: %v", err)
}
if err := fs.WriteFile("/usr/glenda/lib/profile", "font=pelm\n", 2); err != nil {
t.Fatalf("writefile: %v", err)
}
f, err := ninep.Walk(fs.Root(), ninep.Elems("/usr/glenda/lib/profile"))
if err != nil {
t.Fatalf("walk: %v", err)
}
if got, _ := ninep.ReadAll(f); got != "font=pelm\n" {
t.Errorf("got %q", got)
}
// rewriting replaces rather than appends
if err := fs.WriteFile("/usr/glenda/lib/profile", "font=lucida\n", 3); err != nil {
t.Fatalf("rewrite: %v", err)
}
f, _ = ninep.Walk(fs.Root(), ninep.Elems("/usr/glenda/lib/profile"))
if got, _ := ninep.ReadAll(f); got != "font=lucida\n" {
t.Errorf("rewrite got %q", got)
}
}
func TestMkdirAllThroughAFileFails(t *testing.T) {
fs := New("glenda", 1)
fs.WriteFile("/etc", "not a directory", 1)
if _, err := fs.MkdirAll("/etc/passwd", 2); err != ninep.ErrNotDir {
t.Errorf("got %v, want ErrNotDir", err)
}
}
func TestWalkDepthLimit(t *testing.T) {
fs := New("glenda", 1)
elems := []string{}
for i := 0; i <= ninep.MaxDepth; i++ {
elems = append(elems, "x")
}
if _, err := ninep.Walk(fs.Root(), elems); err != ninep.ErrTooDeep {
t.Errorf("got %v, want ErrTooDeep", err)
}
}