2023-01-11 12:13:13 +01:00
|
|
|
package iotools
|
|
|
|
|
|
|
|
import "io"
|
|
|
|
|
2024-07-12 11:39:47 +02:00
|
|
|
// NopCloser is an empty
|
|
|
|
// implementation of io.Closer,
|
|
|
|
// that simply does nothing!
|
|
|
|
type NopCloser struct{}
|
|
|
|
|
|
|
|
func (NopCloser) Close() error { return nil }
|
|
|
|
|
2023-01-11 12:13:13 +01:00
|
|
|
// 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()
|
|
|
|
}
|
|
|
|
|
2024-07-12 11:39:47 +02:00
|
|
|
// CloserCallback wraps io.Closer to add a callback deferred to call just after Close().
|
2023-01-11 12:13:13 +01:00
|
|
|
func CloserCallback(c io.Closer, cb func()) io.Closer {
|
|
|
|
return CloserFunc(func() error {
|
|
|
|
defer cb()
|
|
|
|
return c.Close()
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-07-12 11:39:47 +02:00
|
|
|
// CloserAfterCallback wraps io.Closer to add a callback called just before Close().
|
2023-06-02 10:34:52 +02:00
|
|
|
func CloserAfterCallback(c io.Closer, cb func()) io.Closer {
|
|
|
|
return CloserFunc(func() (err error) {
|
|
|
|
defer func() { err = c.Close() }()
|
|
|
|
cb()
|
|
|
|
return
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-01-11 12:13:13 +01:00
|
|
|
// 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()
|
|
|
|
})
|
|
|
|
}
|