utils.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. Length() is provided as an
  25. // optimization, and must return the same as len() on the result of Encode().
  26. type Encoder interface {
  27. Encode() ([]byte, error)
  28. Length() int
  29. }
  30. // make strings and byte slices encodable for convenience so they can be used as keys
  31. // and/or values in kafka messages
  32. // StringEncoder implements the Encoder interface for Go strings so that you can do things like
  33. // producer.SendMessage(nil, sarama.StringEncoder("hello world"))
  34. type StringEncoder string
  35. func (s StringEncoder) Encode() ([]byte, error) {
  36. return []byte(s), nil
  37. }
  38. func (s StringEncoder) Length() int {
  39. return len(s)
  40. }
  41. // ByteEncoder implements the Encoder interface for Go byte slices so that you can do things like
  42. // producer.SendMessage(nil, sarama.ByteEncoder([]byte{0x00}))
  43. type ByteEncoder []byte
  44. func (b ByteEncoder) Encode() ([]byte, error) {
  45. return b, nil
  46. }
  47. func (b ByteEncoder) Length() int {
  48. return len(b)
  49. }