utils.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package sarama
  2. // make []int32 sortable so we can sort partition numbers
  3. type int32Slice []int32
  4. func (slice int32Slice) Len() int {
  5. return len(slice)
  6. }
  7. func (slice int32Slice) Less(i, j int) bool {
  8. return slice[i] < slice[j]
  9. }
  10. func (slice int32Slice) Swap(i, j int) {
  11. slice[i], slice[j] = slice[j], slice[i]
  12. }
  13. func withRecover(fn func()) {
  14. defer func() {
  15. if PanicHandler != nil {
  16. if err := recover(); err != nil {
  17. PanicHandler(err)
  18. }
  19. }
  20. }()
  21. fn()
  22. }
  23. // Encoder is a simple interface for any type that can be encoded as an array of bytes
  24. // in order to be sent as the key or value of a Kafka message.
  25. type Encoder interface {
  26. Encode() ([]byte, error)
  27. }
  28. // make strings and byte slices encodable for convenience so they can be used as keys
  29. // and/or values in kafka messages
  30. // StringEncoder implements the Encoder interface for Go strings so that you can do things like
  31. // producer.SendMessage(nil, sarama.StringEncoder("hello world"))
  32. type StringEncoder string
  33. func (s StringEncoder) Encode() ([]byte, error) {
  34. return []byte(s), nil
  35. }
  36. // ByteEncoder implements the Encoder interface for Go byte slices so that you can do things like
  37. // producer.SendMessage(nil, sarama.ByteEncoder([]byte{0x00}))
  38. type ByteEncoder []byte
  39. func (b ByteEncoder) Encode() ([]byte, error) {
  40. return b, nil
  41. }