github.com/richardwilkes/toolbox@v1.121.0/xio/context.go (about)

     1  // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the Mozilla Public
     4  // License, version 2.0. If a copy of the MPL was not distributed with
     5  // this file, You can obtain one at http://mozilla.org/MPL/2.0/.
     6  //
     7  // This Source Code Form is "Incompatible With Secondary Licenses", as
     8  // defined by the Mozilla Public License, version 2.0.
     9  
    10  package xio
    11  
    12  import (
    13  	"context"
    14  	"time"
    15  
    16  	"github.com/richardwilkes/toolbox/errs"
    17  )
    18  
    19  // Contexter is an interface that provides a context.
    20  type Contexter interface {
    21  	Context() context.Context
    22  }
    23  
    24  // ContextSleep sleeps for the specified time, or until the context is done. You can check the return error to see if
    25  // the context deadline was exceeded by using errors.Is(err, context.DeadlineExceeded).
    26  func ContextSleep(ctx context.Context, waitTime time.Duration) error {
    27  	timer := time.NewTimer(waitTime)
    28  	defer timer.Stop()
    29  	select {
    30  	case <-ctx.Done():
    31  		err := ctx.Err()
    32  		return errs.NewWithCause(err.Error(), err)
    33  	case <-timer.C:
    34  		return nil
    35  	}
    36  }
    37  
    38  // ContexterWasCanceled checks the context held by the contexter to see if it was canceled.
    39  func ContexterWasCanceled(ctxer Contexter) bool {
    40  	return ContextWasCanceled(ctxer.Context())
    41  }
    42  
    43  // ContextWasCanceled checks the context to see if it was canceled.
    44  func ContextWasCanceled(ctx context.Context) bool {
    45  	select {
    46  	case <-ctx.Done():
    47  		if ctx.Err() != nil {
    48  			return true
    49  		}
    50  	default:
    51  	}
    52  	return false
    53  }