github.com/zhuohuang-hust/src-cbuild@v0.0.0-20230105071821-c7aab3e7c840/mergeCode/libnetwork/idm/idm.go (about)

     1  // Package idm manages reservation/release of numerical ids from a configured set of contiguous ids
     2  package idm
     3  
     4  import (
     5  	"fmt"
     6  
     7  	"github.com/docker/libnetwork/bitseq"
     8  	"github.com/docker/libnetwork/datastore"
     9  )
    10  
    11  // Idm manages the reservation/release of numerical ids from a contiguous set
    12  type Idm struct {
    13  	start  uint64
    14  	end    uint64
    15  	handle *bitseq.Handle
    16  }
    17  
    18  // New returns an instance of id manager for a set of [start-end] numerical ids
    19  func New(ds datastore.DataStore, id string, start, end uint64) (*Idm, error) {
    20  	if id == "" {
    21  		return nil, fmt.Errorf("Invalid id")
    22  	}
    23  	if end <= start {
    24  		return nil, fmt.Errorf("Invalid set range: [%d, %d]", start, end)
    25  	}
    26  
    27  	h, err := bitseq.NewHandle("idm", ds, id, 1+end-start)
    28  	if err != nil {
    29  		return nil, fmt.Errorf("failed to initialize bit sequence handler: %s", err.Error())
    30  	}
    31  
    32  	return &Idm{start: start, end: end, handle: h}, nil
    33  }
    34  
    35  // GetID returns the first available id in the set
    36  func (i *Idm) GetID() (uint64, error) {
    37  	if i.handle == nil {
    38  		return 0, fmt.Errorf("ID set is not initialized")
    39  	}
    40  	ordinal, err := i.handle.SetAny()
    41  	return i.start + ordinal, err
    42  }
    43  
    44  // GetSpecificID tries to reserve the specified id
    45  func (i *Idm) GetSpecificID(id uint64) error {
    46  	if i.handle == nil {
    47  		return fmt.Errorf("ID set is not initialized")
    48  	}
    49  
    50  	if id < i.start || id > i.end {
    51  		return fmt.Errorf("Requested id does not belong to the set")
    52  	}
    53  
    54  	return i.handle.Set(id - i.start)
    55  }
    56  
    57  // Release releases the specified id
    58  func (i *Idm) Release(id uint64) {
    59  	i.handle.Unset(id - i.start)
    60  }