github.com/ghodss/etcd@v0.3.1-0.20140417172404-cc329bfa55cb/mod/lock/v2/lock_nodes.go (about) 1 package v2 2 3 import ( 4 "path" 5 "sort" 6 "strconv" 7 8 "github.com/coreos/etcd/third_party/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 // Find the node with the largest index in the lockNodes that is smaller than the given index. Also return the lastModified index of that node. 45 func (s lockNodes) PrevIndex(index int) (int, int) { 46 sort.Sort(s) 47 48 // Iterate over each node to find the given index. We keep track of the 49 // previous index on each iteration so we can return it when we match the 50 // index we're looking for. 51 var prevIndex int 52 for _, node := range s.Nodes { 53 idx, _ := strconv.Atoi(path.Base(node.Key)) 54 if index == idx { 55 return prevIndex, int(node.ModifiedIndex) 56 } 57 prevIndex = idx 58 } 59 return 0, 0 60 }