github.com/v2fly/v2ray-core/v4@v4.45.2/common/interfaces.go (about)

     1  package common
     2  
     3  import "github.com/v2fly/v2ray-core/v4/common/errors"
     4  
     5  // Closable is the interface for objects that can release its resources.
     6  //
     7  // v2ray:api:beta
     8  type Closable interface {
     9  	// Close release all resources used by this object, including goroutines.
    10  	Close() error
    11  }
    12  
    13  // Interruptible is an interface for objects that can be stopped before its completion.
    14  //
    15  // v2ray:api:beta
    16  type Interruptible interface {
    17  	Interrupt()
    18  }
    19  
    20  // Close closes the obj if it is a Closable.
    21  //
    22  // v2ray:api:beta
    23  func Close(obj interface{}) error {
    24  	if c, ok := obj.(Closable); ok {
    25  		return c.Close()
    26  	}
    27  	return nil
    28  }
    29  
    30  // Interrupt calls Interrupt() if object implements Interruptible interface, or Close() if the object implements Closable interface.
    31  //
    32  // v2ray:api:beta
    33  func Interrupt(obj interface{}) error {
    34  	if c, ok := obj.(Interruptible); ok {
    35  		c.Interrupt()
    36  		return nil
    37  	}
    38  	return Close(obj)
    39  }
    40  
    41  // Runnable is the interface for objects that can start to work and stop on demand.
    42  type Runnable interface {
    43  	// Start starts the runnable object. Upon the method returning nil, the object begins to function properly.
    44  	Start() error
    45  
    46  	Closable
    47  }
    48  
    49  // HasType is the interface for objects that knows its type.
    50  type HasType interface {
    51  	// Type returns the type of the object.
    52  	// Usually it returns (*Type)(nil) of the object.
    53  	Type() interface{}
    54  }
    55  
    56  // ChainedClosable is a Closable that consists of multiple Closable objects.
    57  type ChainedClosable []Closable
    58  
    59  // Close implements Closable.
    60  func (cc ChainedClosable) Close() error {
    61  	var errs []error
    62  	for _, c := range cc {
    63  		if err := c.Close(); err != nil {
    64  			errs = append(errs, err)
    65  		}
    66  	}
    67  	return errors.Combine(errs...)
    68  }