-
Notifications
You must be signed in to change notification settings - Fork 18
/
bounded.go
107 lines (81 loc) · 1.98 KB
/
bounded.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package bounded
import (
"errors"
"fmt"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"os"
)
var ErrExhausted = errors.New("filesystem limit exhausted")
type FileSystem struct {
maxFiles int
maxBytes int
filesCreated int
bytesWritten int
billy.Filesystem
}
type File struct {
bfs *FileSystem
billy.File
}
func NewFilesystem(maxBytes, maxFiles int) billy.Filesystem {
return &FileSystem{
maxFiles: maxFiles,
maxBytes: maxBytes,
Filesystem: memfs.New(),
}
}
func (bfs *FileSystem) Create(filename string) (billy.File, error) {
return bfs.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
}
func (bfs *FileSystem) Open(filename string) (billy.File, error) {
return bfs.OpenFile(filename, os.O_RDONLY, 0)
}
func (bfs *FileSystem) OpenFile(filename string, flag int, perm os.FileMode) (billy.File, error) {
if err := bfs.moreFiles(1); err != nil {
return nil, err
}
file, err := bfs.Filesystem.OpenFile(filename, flag, perm)
// Accounting
if err == nil && (flag&os.O_CREATE) != 0 {
bfs.filesCreated++
}
return &File{
bfs: bfs,
File: file,
}, err
}
func (bfs *FileSystem) MkdirAll(filename string, perm os.FileMode) error {
if err := bfs.moreFiles(1); err != nil {
return err
}
err := bfs.Filesystem.MkdirAll(filename, perm)
// Accounting
if err == nil {
bfs.filesCreated++
}
return err
}
func (bfs *FileSystem) moreFiles(n int) error {
if (bfs.filesCreated + n) > bfs.maxFiles {
return fmt.Errorf("%w: attempted to create more than %d files", ErrExhausted, bfs.maxFiles)
}
return nil
}
func (bfs *FileSystem) moreBytes(n int) error {
if (bfs.bytesWritten + n) > bfs.maxBytes {
return fmt.Errorf("%w: attempted to write more than %d bytes", ErrExhausted, bfs.maxBytes)
}
return nil
}
func (bf *File) Write(p []byte) (int, error) {
if err := bf.bfs.moreBytes(len(p)); err != nil {
return -1, err
}
n, err := bf.File.Write(p)
// Accounting
if err == nil {
bf.bfs.bytesWritten += n
}
return n, err
}