github.com/Uhtred009/v2ray-core-1@v4.31.2+incompatible/transport/pipe/pipe.go (about)

     1  package pipe
     2  
     3  import (
     4  	"context"
     5  
     6  	"v2ray.com/core/common/signal"
     7  	"v2ray.com/core/common/signal/done"
     8  	"v2ray.com/core/features/policy"
     9  )
    10  
    11  // Option for creating new Pipes.
    12  type Option func(*pipeOption)
    13  
    14  // WithoutSizeLimit returns an Option for Pipe to have no size limit.
    15  func WithoutSizeLimit() Option {
    16  	return func(opt *pipeOption) {
    17  		opt.limit = -1
    18  	}
    19  }
    20  
    21  // WithSizeLimit returns an Option for Pipe to have the given size limit.
    22  func WithSizeLimit(limit int32) Option {
    23  	return func(opt *pipeOption) {
    24  		opt.limit = limit
    25  	}
    26  }
    27  
    28  // DiscardOverflow returns an Option for Pipe to discard writes if full.
    29  func DiscardOverflow() Option {
    30  	return func(opt *pipeOption) {
    31  		opt.discardOverflow = true
    32  	}
    33  }
    34  
    35  // OptionsFromContext returns a list of Options from context.
    36  func OptionsFromContext(ctx context.Context) []Option {
    37  	var opt []Option
    38  
    39  	bp := policy.BufferPolicyFromContext(ctx)
    40  	if bp.PerConnection >= 0 {
    41  		opt = append(opt, WithSizeLimit(bp.PerConnection))
    42  	} else {
    43  		opt = append(opt, WithoutSizeLimit())
    44  	}
    45  
    46  	return opt
    47  }
    48  
    49  // New creates a new Reader and Writer that connects to each other.
    50  func New(opts ...Option) (*Reader, *Writer) {
    51  	p := &pipe{
    52  		readSignal:  signal.NewNotifier(),
    53  		writeSignal: signal.NewNotifier(),
    54  		done:        done.New(),
    55  		option: pipeOption{
    56  			limit: -1,
    57  		},
    58  	}
    59  
    60  	for _, opt := range opts {
    61  		opt(&(p.option))
    62  	}
    63  
    64  	return &Reader{
    65  			pipe: p,
    66  		}, &Writer{
    67  			pipe: p,
    68  		}
    69  }