github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/ctxext/extensions.go (about)

     1  package ctxext
     2  
     3  import "sync/atomic"
     4  
     5  type ContextExtensionID int32
     6  
     7  var currentContextExtensionID int32
     8  
     9  type ContextExtension interface {
    10  	ExtensionID() ContextExtensionID
    11  }
    12  
    13  type ContextExtensions struct {
    14  	extensions []ContextExtension
    15  }
    16  
    17  func NewContextExtensions() *ContextExtensions {
    18  	ex := &ContextExtensions{
    19  		extensions: make([]ContextExtension, 3),
    20  	}
    21  
    22  	return ex
    23  }
    24  
    25  func NextContextExtensionID() ContextExtensionID {
    26  	id := atomic.AddInt32(&currentContextExtensionID, 1)
    27  	return ContextExtensionID(id)
    28  }
    29  
    30  func (ex *ContextExtensions) Get(id ContextExtensionID) ContextExtension {
    31  	return ex.extensions[id]
    32  }
    33  
    34  func (ex *ContextExtensions) Set(extension ContextExtension) {
    35  	id := int32(extension.ExtensionID())
    36  	if id >= int32(len(ex.extensions)) {
    37  		newExtensions := make([]ContextExtension, id*2)
    38  		copy(newExtensions, ex.extensions)
    39  		ex.extensions = newExtensions
    40  	}
    41  	ex.extensions[id] = extension
    42  }