forked from sajari/storage
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmem.go
112 lines (95 loc) · 1.81 KB
/
mem.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
108
109
110
111
112
package storage
import (
"bytes"
"io"
"io/ioutil"
"strings"
"sync"
"time"
"golang.org/x/net/context"
)
type memFile struct {
data []byte
name string
modTime time.Time
}
func (f *memFile) readCloser() io.ReadCloser {
return ioutil.NopCloser(bytes.NewReader(f.data))
}
func (f *memFile) size() int64 {
return int64(len(f.data))
}
// Mem creates a a basic in-memory implementation of FS.
func Mem() FS {
return &mem{
data: make(map[string]*memFile),
}
}
type mem struct {
sync.RWMutex
data map[string]*memFile
}
// Open implements FS.
func (m *mem) Open(_ context.Context, path string) (*File, error) {
m.RLock()
f, ok := m.data[path]
m.RUnlock()
if ok {
return &File{
ReadCloser: f.readCloser(),
Name: f.name,
ModTime: f.modTime,
Size: f.size(),
}, nil
}
return nil, ¬ExistError{
Path: path,
}
}
type writingFile struct {
*bytes.Buffer
path string
m *mem
}
func (wf *writingFile) Close() error {
wf.m.Lock()
wf.m.data[wf.path] = &memFile{
data: wf.Buffer.Bytes(),
name: wf.path,
modTime: time.Now(),
}
wf.m.Unlock()
return nil
}
// Create implements FS. NB: Callers must close the io.WriteCloser to create the file.
func (m *mem) Create(_ context.Context, path string) (io.WriteCloser, error) {
return &writingFile{
Buffer: &bytes.Buffer{},
path: path,
m: m,
}, nil
}
// Delete implements FS.
func (m *mem) Delete(_ context.Context, path string) error {
m.Lock()
delete(m.data, path)
m.Unlock()
return nil
}
// Walk implements FS.
func (m *mem) Walk(_ context.Context, path string, fn WalkFn) error {
var list []string
m.RLock()
for k := range m.data {
if strings.HasPrefix(k, path) {
list = append(list, k)
}
}
m.RUnlock()
for _, k := range list {
if err := fn(k); err != nil {
return err
}
}
return nil
}