github.com/biogo/store@v0.0.0-20201120204734-aad293a2328f/llrb/llrb_example_test.go (about) 1 // Copyright ©2012 The bíogo Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package llrb_test 6 7 import ( 8 "fmt" 9 10 "github.com/biogo/store/llrb" 11 ) 12 13 type ( 14 Int int 15 IntUpperBound int 16 ) 17 18 func (c Int) Compare(b llrb.Comparable) int { 19 switch i := b.(type) { 20 case Int: 21 return int(c - i) 22 case IntUpperBound: 23 return int(c) - int(i) 24 } 25 panic("unknown type") 26 } 27 28 func (c IntUpperBound) Compare(b llrb.Comparable) int { 29 var d int 30 switch i := b.(type) { 31 case Int: 32 d = int(c) - int(i) 33 case IntUpperBound: 34 d = int(c - i) 35 } 36 if d == 0 { 37 return 1 38 } 39 return d 40 } 41 42 func Example() { 43 values := []int{0, 1, 2, 3, 4, 2, 3, 5, 5, 65, 32, 3, 23} 44 45 // Insert using a type that reports equality: 46 { 47 t := &llrb.Tree{} 48 for _, v := range values { 49 t.Insert(Int(v)) // Insert with replacement. 50 } 51 52 results := []int(nil) 53 // More efficiently retrieved using Get(Int(3))... 54 t.DoMatching(func(c llrb.Comparable) (done bool) { 55 results = append(results, int(c.(Int))) 56 return 57 }, Int(3)) 58 59 fmt.Println("With replacement: ", results) 60 } 61 62 // Insert using a type that does not report equality: 63 { 64 t := &llrb.Tree{} 65 for _, v := range values { 66 t.Insert(IntUpperBound(v)) // Insert without replacement. 67 } 68 69 results := []int(nil) 70 t.DoMatching(func(c llrb.Comparable) (done bool) { 71 results = append(results, int(c.(IntUpperBound))) 72 return 73 }, Int(3)) 74 75 fmt.Println("Without replacement:", results) 76 } 77 78 // Output: 79 // With replacement: [3] 80 // Without replacement: [3 3 3] 81 }