github.com/pion/dtls/v2@v2.2.12/internal/closer/closer.go (about)

     1  // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
     2  // SPDX-License-Identifier: MIT
     3  
     4  // Package closer provides signaling channel for shutdown
     5  package closer
     6  
     7  import (
     8  	"context"
     9  )
    10  
    11  // Closer allows for each signaling a channel for shutdown
    12  type Closer struct {
    13  	ctx       context.Context
    14  	closeFunc func()
    15  }
    16  
    17  // NewCloser creates a new instance of Closer
    18  func NewCloser() *Closer {
    19  	ctx, closeFunc := context.WithCancel(context.Background())
    20  	return &Closer{
    21  		ctx:       ctx,
    22  		closeFunc: closeFunc,
    23  	}
    24  }
    25  
    26  // NewCloserWithParent creates a new instance of Closer with a parent context
    27  func NewCloserWithParent(ctx context.Context) *Closer {
    28  	ctx, closeFunc := context.WithCancel(ctx)
    29  	return &Closer{
    30  		ctx:       ctx,
    31  		closeFunc: closeFunc,
    32  	}
    33  }
    34  
    35  // Done returns a channel signaling when it is done
    36  func (c *Closer) Done() <-chan struct{} {
    37  	return c.ctx.Done()
    38  }
    39  
    40  // Err returns an error of the context
    41  func (c *Closer) Err() error {
    42  	return c.ctx.Err()
    43  }
    44  
    45  // Close sends a signal to trigger the ctx done channel
    46  func (c *Closer) Close() {
    47  	c.closeFunc()
    48  }