blob: f3d4814ba3ef4af4646af5f2b180b289ba490065 (
plain)
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
|
package iotools
import "io"
// NopCloser is an empty
// implementation of io.Closer,
// that simply does nothing!
type NopCloser struct{}
func (NopCloser) Close() error { return nil }
// CloserFunc is a function signature which allows
// a function to implement the io.Closer type.
type CloserFunc func() error
func (c CloserFunc) Close() error {
return c()
}
// CloserCallback wraps io.Closer to add a callback deferred to call just after Close().
func CloserCallback(c io.Closer, cb func()) io.Closer {
return CloserFunc(func() error {
defer cb()
return c.Close()
})
}
// CloserAfterCallback wraps io.Closer to add a callback called just before Close().
func CloserAfterCallback(c io.Closer, cb func()) io.Closer {
return CloserFunc(func() (err error) {
defer func() { err = c.Close() }()
cb()
return
})
}
// CloseOnce wraps an io.Closer to ensure it only performs the close logic once.
func CloseOnce(c io.Closer) io.Closer {
return CloserFunc(func() error {
if c == nil {
// already run.
return nil
}
// Acquire.
cptr := c
c = nil
// Call the closer.
return cptr.Close()
})
}
|