encoder.go 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. package exporter
  2. import "encoding"
  3. // Encoder[T] is a generic interface for encoding an instance of a T type into a byte slice.
  4. type Encoder[T any] interface {
  5. Encode(*T) ([]byte, error)
  6. }
  7. // BinaryMarshalerPtr[T] is a generic constraint to ensure types passed to the encoder implement
  8. // encoding.BinaryMarshaler and are pointers to T.
  9. type BinaryMarshalerPtr[T any] interface {
  10. encoding.BinaryMarshaler
  11. *T
  12. }
  13. // BingenEncoder[T, U] is a generic encoder that uses the BinaryMarshaler interface to encode data.
  14. // It supports any type T that implements the encoding.BinaryMarshaler interface.
  15. type BingenEncoder[T any, U BinaryMarshalerPtr[T]] struct{}
  16. // NewBingenEncoder creates an `Encoder[T]` implementation which supports binary encoding for the `T`
  17. // type.
  18. func NewBingenEncoder[T any, U BinaryMarshalerPtr[T]]() Encoder[T] {
  19. return new(BingenEncoder[T, U])
  20. }
  21. // Encode encodes the provided data of type T into a byte slice using the BinaryMarshaler interface.
  22. func (b *BingenEncoder[T, U]) Encode(data *T) ([]byte, error) {
  23. var bingenData U = data
  24. return bingenData.MarshalBinary()
  25. }