forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
closers.go
39 lines (32 loc) · 799 Bytes
/
closers.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
// Copyright (C) 2019-2021, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package wrappers
import (
"io"
"sync"
)
// Closer is a nice utility for closing a group of objects while reporting an
// error if one occurs.
type Closer struct {
lock sync.Mutex
closers []io.Closer
}
// Add a new object to be closed.
func (c *Closer) Add(closer io.Closer) {
c.lock.Lock()
defer c.lock.Unlock()
c.closers = append(c.closers, closer)
}
// Close closes each of the closers add to [c] and returns the first error
// that occurs or nil if no error occurs.
func (c *Closer) Close() error {
c.lock.Lock()
closers := c.closers
c.closers = nil
c.lock.Unlock()
errs := Errs{}
for _, closer := range closers {
errs.Add(closer.Close())
}
return errs.Err
}