Debian Codegraph @

common/types/closer.go

raw
1 // Copyright 2024 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package types
15
16 import "sync"
17
18 type Closer interface {
19 Close() error
20 }
21
22 // CloserFunc is a convenience type to create a Closer from a function.
23 type CloserFunc func() error
24
25 func (f CloserFunc) Close() error {
26 return f()
27 }
28
29 type CloseAdder interface {
30 Add(Closer)
31 }
32
33 type Closers struct {
34 mu sync.Mutex
35 cs []Closer
36 }
37
38 func (cs *Closers) Add(c Closer) {
39 cs.mu.Lock()
40 defer cs.mu.Unlock()
41 cs.cs = append(cs.cs, c)
42 }
43
44 func (cs *Closers) Close() error {
45 cs.mu.Lock()
46 defer cs.mu.Unlock()
47 for _, c := range cs.cs {
48 c.Close()
49 }
50
51 cs.cs = cs.cs[:0]
52
53 return nil
54 }