github.com/ydb-platform/ydb-go-sdk/v3@v3.89.2/internal/xcontext/done.go (about)

     1  package xcontext
     2  
     3  import (
     4  	"context"
     5  	"time"
     6  )
     7  
     8  type doneCtx <-chan struct{}
     9  
    10  func (done doneCtx) Deadline() (deadline time.Time, ok bool) {
    11  	return
    12  }
    13  
    14  func (done doneCtx) Done() <-chan struct{} {
    15  	return done
    16  }
    17  
    18  func (done doneCtx) Err() error {
    19  	select {
    20  	case <-done:
    21  		return context.Canceled
    22  	default:
    23  		return nil
    24  	}
    25  }
    26  
    27  func (done doneCtx) Value(key any) any {
    28  	return nil
    29  }
    30  
    31  func WithDone(parent context.Context, done <-chan struct{}) (context.Context, context.CancelFunc) {
    32  	ctx, cancel := context.WithCancel(parent)
    33  	stop := context.AfterFunc(doneCtx(done), func() {
    34  		cancel()
    35  	})
    36  
    37  	return ctx, func() {
    38  		stop()
    39  		cancel()
    40  	}
    41  }