github.com/jpetazzo/etcd@v0.2.1-0.20140113055439-97f1363afac5/mod/lock/v2/lock_nodes.go (about)

     1  package v2
     2  
     3  import (
     4  	"path"
     5  	"sort"
     6  	"strconv"
     7  
     8  	"github.com/coreos/go-etcd/etcd"
     9  )
    10  
    11  // lockNodes is a wrapper for go-etcd's Nodes to allow for sorting by numeric key.
    12  type lockNodes struct {
    13  	etcd.Nodes
    14  }
    15  
    16  // Less sorts the nodes by key (numerically).
    17  func (s lockNodes) Less(i, j int) bool {
    18  	a, _ := strconv.Atoi(path.Base(s.Nodes[i].Key))
    19  	b, _ := strconv.Atoi(path.Base(s.Nodes[j].Key))
    20  	return a < b
    21  }
    22  
    23  // Retrieves the first node in the set of lock nodes.
    24  func (s lockNodes) First() *etcd.Node {
    25  	sort.Sort(s)
    26  	if len(s.Nodes) > 0 {
    27  		return &s.Nodes[0]
    28  	}
    29  	return nil
    30  }
    31  
    32  // Retrieves the first node with a given value.
    33  func (s lockNodes) FindByValue(value string) (*etcd.Node, int) {
    34  	sort.Sort(s)
    35  
    36  	for i, node := range s.Nodes {
    37  		if node.Value == value {
    38  			return &node, i
    39  		}
    40  	}
    41  	return nil, 0
    42  }
    43  
    44  // Retrieves the index that occurs before a given index.
    45  func (s lockNodes) PrevIndex(index int) int {
    46  	sort.Sort(s)
    47  
    48  	var prevIndex int
    49  	for _, node := range s.Nodes {
    50  		idx, _ := strconv.Atoi(path.Base(node.Key))
    51  		if index == idx {
    52  			return prevIndex
    53  		}
    54  		prevIndex = idx
    55  	}
    56  	return 0
    57  }