Skip to content

Instantly share code, notes, and snippets.

@tecbot
Created February 13, 2014 14:22
Show Gist options
  • Save tecbot/8975820 to your computer and use it in GitHub Desktop.
Save tecbot/8975820 to your computer and use it in GitHub Desktop.
package gorocksdb
// #include "rocksdb/c.h"
// #include "gorocksdb.h"
import "C"
import (
"unsafe"
"fmt"
)
var handlerPointers = make(map[unsafe.Pointer]ComparatorHandler)
// A Comparator object provides a total order across slices that are
// used as keys in an sstable or a database.
type Comparator struct {
c *C.rocksdb_comparator_t
}
type ComparatorHandler interface {
// Three-way comparison. Returns value:
// < 0 iff "a" < "b",
// == 0 iff "a" == "b",
// > 0 iff "a" > "b"
Compare(a []byte, b []byte) int
// The name of the comparator.
Name() string
}
// NewComparator creates a new comparator for the given handler.
func NewComparator(handler ComparatorHandler) *Comparator {
ptr := unsafe.Pointer(&handler)
handlerPointers[ptr] = handler
return NewNativeComparator(C.gorocksdb_comparator_create(ptr))
}
// NewNativeComparator allocates a Comparator object.
func NewNativeComparator(c *C.rocksdb_comparator_t) *Comparator {
return &Comparator{c}
}
// Destroy deallocates the Comparator object.
func (self *Comparator) Destroy() {
C.rocksdb_comparator_destroy(self.c)
}
//export gorocksdb_comparator_compare
func gorocksdb_comparator_compare(ptr unsafe.Pointer, cKeyA *C.char, cKeyALen C.size_t, cKeyB *C.char, cKeyBLen C.size_t) C.int {
handler, present := handlerPointers[ptr]
if !present {
panic(fmt.Sprintf("no handler for pointer %v found", ptr))
}
keyA := CharToByte(cKeyA, cKeyALen)
keyB := CharToByte(cKeyB, cKeyBLen)
compare := handler.Compare(keyA, keyB)
return C.int(compare)
}
//export gorocksdb_comparator_name
func gorocksdb_comparator_name(ptr unsafe.Pointer) *C.char {
handler, present := handlerPointers[ptr]
if !present {
panic(fmt.Sprintf("no handler for pointer %v found", ptr))
}
return StringToChar(handler.Name())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment