github.com/livekit/protocol@v1.39.3/utils/closers.go (about)

     1  // Copyright 2023 LiveKit, Inc.
     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  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package utils
    16  
    17  import (
    18  	"io"
    19  
    20  	"go.uber.org/multierr"
    21  )
    22  
    23  type Closers []io.Closer
    24  
    25  func CombineClosers(cs ...io.Closer) Closers {
    26  	return append([]io.Closer{}, cs...)
    27  }
    28  
    29  func (s *Closers) Close() error {
    30  	var err error
    31  	for _, c := range *s {
    32  		if c != nil {
    33  			err = multierr.Append(err, c.Close())
    34  		}
    35  	}
    36  
    37  	*s = (*s)[:0]
    38  
    39  	return err
    40  }
    41  
    42  type CloseFuncType interface {
    43  	~func() error | ~func()
    44  }
    45  
    46  func CloseFunc[T CloseFuncType](fn T) io.Closer {
    47  	return closeFunc[T]{fn}
    48  }
    49  
    50  type closeFunc[T CloseFuncType] struct {
    51  	fn T
    52  }
    53  
    54  func (f closeFunc[T]) Close() error {
    55  	switch fn := any(f.fn).(type) {
    56  	case func() error:
    57  		return fn()
    58  	case func():
    59  		fn()
    60  	}
    61  	return nil
    62  }