order.go 1.44 KB
Newer Older
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
1 2 3
package query

import (
4 5
	"bytes"
	"strings"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6 7 8 9
)

// Order is an object used to order objects
type Order interface {
10
	Compare(a, b Entry) int
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
11 12
}

13 14 15 16 17
// OrderByFunction orders the results based on the result of the given function.
type OrderByFunction func(a, b Entry) int

func (o OrderByFunction) Compare(a, b Entry) int {
	return o(a, b)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
18 19
}

20 21 22 23 24 25
// OrderByValue is used to signal to datastores they should apply internal
// orderings.
type OrderByValue struct{}

func (o OrderByValue) Compare(a, b Entry) int {
	return bytes.Compare(a.Value, b.Value)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
26 27 28
}

// OrderByValueDescending is used to signal to datastores they
29 30
// should apply internal orderings.
type OrderByValueDescending struct{}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31

32 33
func (o OrderByValueDescending) Compare(a, b Entry) int {
	return -bytes.Compare(a.Value, b.Value)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
34 35 36 37 38
}

// OrderByKey
type OrderByKey struct{}

39 40
func (o OrderByKey) Compare(a, b Entry) int {
	return strings.Compare(a.Key, b.Key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41 42 43 44 45
}

// OrderByKeyDescending
type OrderByKeyDescending struct{}

46 47
func (o OrderByKeyDescending) Compare(a, b Entry) int {
	return -strings.Compare(a.Key, b.Key)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
48
}
Steven Allen's avatar
Steven Allen committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66

// Less returns true if a comes before b with the requested orderings.
func Less(orders []Order, a, b Entry) bool {
	for _, cmp := range orders {
		switch cmp.Compare(a, b) {
		case 0:
		case -1:
			return true
		case 1:
			return false
		}
	}

	// This gives us a *stable* sort for free. We don't care
	// preserving the order from the underlying datastore
	// because it's undefined.
	return a.Key < b.Key
}