diff --git a/example/ex1.go b/example/ex1.go index 6ebe4a6..a3d6a5e 100644 --- a/example/ex1.go +++ b/example/ex1.go @@ -1,26 +1,41 @@ package main import ( - "fmt" + "log" + "github.com/petar/GoLLRB/llrb" ) -func lessInt(a, b interface{}) bool { return a.(int) < b.(int) } +// SampleData will be sorted by Text field +type SampleData struct { + Text string + Data []byte +} + +// Less method, implements llrb.Item interface for SampleData structure +func (a *SampleData) Less(b llrb.Item) bool { return a.Text < b.(*SampleData).Text } func main() { - tree := llrb.New(lessInt) - tree.ReplaceOrInsert(1) - tree.ReplaceOrInsert(2) - tree.ReplaceOrInsert(3) - tree.ReplaceOrInsert(4) - tree.DeleteMin() - tree.Delete(4) - c := tree.IterAscend() - for { - u := <-c - if u == nil { - break - } - fmt.Printf("%d\n", int(u.(int))) - } + tree := llrb.New() + + // Inserting sample data + neo := &SampleData{Text: "Neo", Data: []byte("The Matrix")} + bob := &SampleData{Text: "Bob", Data: []byte{42}} + tree.ReplaceOrInsert(neo) + tree.ReplaceOrInsert(bob) + tree.ReplaceOrInsert(&SampleData{Text: "Alice", Data: []byte("Please, delete me!")}) + tree.ReplaceOrInsert(&SampleData{Text: "Boris", Data: []byte(bob.Text)}) + tree.ReplaceOrInsert(&SampleData{Text: "Petar", Data: []byte{'G', 'o', 0x4c, 0x4c, 0x52, 0x42}}) + + tree.DeleteMin() // Alice will be deleted + tree.Delete(neo) // Neo is deleted + + // Filtering SampleData items so that + // SampleData.Text should start with "Bo" + filter := &SampleData{Text: "Bo", Data: nil} + tree.AscendGreaterOrEqual(filter, func(i llrb.Item) bool { + s := i.(*SampleData) + log.Printf("%q: %q", s.Text, s.Data) + return true + }) }