github.com/haraldrudell/parl@v0.4.176/pqs/assigned-priority.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package pqs
     7  
     8  import (
     9  	"golang.org/x/exp/constraints"
    10  )
    11  
    12  // AssignedPriority contains the assigned priority for a priority-queue element
    13  //   - V is the element value type whose pointer-value provides identity
    14  //   - P is the priority, a descending-ordered type
    15  //   - SetPriority updates the priority
    16  //   - Cmp makes AssignedPriority ordered
    17  type AssignedPriority[V any, P constraints.Ordered] struct {
    18  	Priority P   // the main sort value, ordered high to low
    19  	Index    int // insertion order: lowest/earliest value first: distinguishes between equal priorities
    20  	Value    *V  // the pointer provides identity for this priority
    21  }
    22  
    23  func NewAssignedPriority[V any, P constraints.Ordered](priority P, index int, value *V) (assignedPriority *AssignedPriority[V, P]) {
    24  	return &AssignedPriority[V, P]{Priority: priority, Index: index, Value: value}
    25  }
    26  
    27  func (ap *AssignedPriority[V, P]) SetPriority(priority P) {
    28  	ap.Priority = priority
    29  }
    30  
    31  // Cmp sorts descending: -1 results appears first
    32  func (a *AssignedPriority[V, P]) Cmp(b *AssignedPriority[V, P]) (result int) {
    33  	if a.Priority > b.Priority {
    34  		return -1
    35  	} else if a.Priority < b.Priority {
    36  		return 1
    37  	} else if a.Index < b.Index {
    38  		return -1
    39  	} else if a.Index > b.Index {
    40  		return 1
    41  	}
    42  	return 0
    43  }