-
Notifications
You must be signed in to change notification settings - Fork 1
/
gatefs.go
93 lines (76 loc) · 1.93 KB
/
gatefs.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
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package gatefs provides an implementation of the FileSystem
// interface that wraps another FileSystem and limits its concurrency.
package gatefs // import "github.com/april1989/origin-go-tools/godoc/vfs/gatefs"
import (
"fmt"
"os"
"github.com/april1989/origin-go-tools/godoc/vfs"
)
// New returns a new FileSystem that delegates to fs.
// If gateCh is non-nil and buffered, it's used as a gate
// to limit concurrency on calls to fs.
func New(fs vfs.FileSystem, gateCh chan bool) vfs.FileSystem {
if cap(gateCh) == 0 {
return fs
}
return gatefs{fs, gate(gateCh)}
}
type gate chan bool
func (g gate) enter() { g <- true }
func (g gate) leave() { <-g }
type gatefs struct {
fs vfs.FileSystem
gate
}
func (fs gatefs) String() string {
return fmt.Sprintf("gated(%s, %d)", fs.fs.String(), cap(fs.gate))
}
func (fs gatefs) RootType(path string) vfs.RootType {
return fs.fs.RootType(path)
}
func (fs gatefs) Open(p string) (vfs.ReadSeekCloser, error) {
fs.enter()
defer fs.leave()
rsc, err := fs.fs.Open(p)
if err != nil {
return nil, err
}
return gatef{rsc, fs.gate}, nil
}
func (fs gatefs) Lstat(p string) (os.FileInfo, error) {
fs.enter()
defer fs.leave()
return fs.fs.Lstat(p)
}
func (fs gatefs) Stat(p string) (os.FileInfo, error) {
fs.enter()
defer fs.leave()
return fs.fs.Stat(p)
}
func (fs gatefs) ReadDir(p string) ([]os.FileInfo, error) {
fs.enter()
defer fs.leave()
return fs.fs.ReadDir(p)
}
type gatef struct {
rsc vfs.ReadSeekCloser
gate
}
func (f gatef) Read(p []byte) (n int, err error) {
f.enter()
defer f.leave()
return f.rsc.Read(p)
}
func (f gatef) Seek(offset int64, whence int) (ret int64, err error) {
f.enter()
defer f.leave()
return f.rsc.Seek(offset, whence)
}
func (f gatef) Close() error {
f.enter()
defer f.leave()
return f.rsc.Close()
}