1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2025-02-20 23:47:21 -05:00
v2fly/transport/pipe/pipe.go

70 lines
1.4 KiB
Go
Raw Normal View History

2018-04-16 14:57:13 +02:00
package pipe
import (
2018-05-25 12:08:28 +02:00
"context"
"github.com/v2fly/v2ray-core/v5/common/signal"
"github.com/v2fly/v2ray-core/v5/common/signal/done"
"github.com/v2fly/v2ray-core/v5/features/policy"
2018-04-16 14:57:13 +02:00
)
2018-05-25 23:20:24 +02:00
// Option for creating new Pipes.
2018-11-14 12:31:59 +01:00
type Option func(*pipeOption)
2018-04-16 14:57:13 +02:00
2018-09-03 00:56:43 +02:00
// WithoutSizeLimit returns an Option for Pipe to have no size limit.
2018-04-16 14:57:13 +02:00
func WithoutSizeLimit() Option {
2018-11-14 12:31:59 +01:00
return func(opt *pipeOption) {
opt.limit = -1
2018-04-16 14:57:13 +02:00
}
}
2018-09-03 00:56:43 +02:00
// WithSizeLimit returns an Option for Pipe to have the given size limit.
2018-04-16 14:57:13 +02:00
func WithSizeLimit(limit int32) Option {
2018-11-14 12:31:59 +01:00
return func(opt *pipeOption) {
opt.limit = limit
2018-04-16 14:57:13 +02:00
}
}
2018-09-03 00:56:43 +02:00
// DiscardOverflow returns an Option for Pipe to discard writes if full.
func DiscardOverflow() Option {
2018-11-14 12:31:59 +01:00
return func(opt *pipeOption) {
opt.discardOverflow = true
2018-09-03 00:56:43 +02:00
}
}
// OptionsFromContext returns a list of Options from context.
2018-05-25 12:08:28 +02:00
func OptionsFromContext(ctx context.Context) []Option {
var opt []Option
2018-10-11 22:34:31 +02:00
bp := policy.BufferPolicyFromContext(ctx)
2018-05-25 13:12:00 +02:00
if bp.PerConnection >= 0 {
opt = append(opt, WithSizeLimit(bp.PerConnection))
2018-05-25 12:08:28 +02:00
} else {
opt = append(opt, WithoutSizeLimit())
}
return opt
}
2018-04-17 00:45:38 +02:00
// New creates a new Reader and Writer that connects to each other.
2018-04-16 14:57:13 +02:00
func New(opts ...Option) (*Reader, *Writer) {
p := &pipe{
readSignal: signal.NewNotifier(),
writeSignal: signal.NewNotifier(),
2018-06-09 04:47:37 +02:00
done: done.New(),
2018-11-14 12:31:59 +01:00
option: pipeOption{
limit: -1,
},
2018-04-16 14:57:13 +02:00
}
for _, opt := range opts {
2018-11-14 12:31:59 +01:00
opt(&(p.option))
2018-04-16 14:57:13 +02:00
}
return &Reader{
pipe: p,
}, &Writer{
pipe: p,
}
}