text_marshaler_struct_test.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package test
  2. import (
  3. "bytes"
  4. "encoding"
  5. "encoding/base64"
  6. "strings"
  7. )
  8. func init() {
  9. testCases = append(testCases,
  10. (*structTextMarshaler)(nil),
  11. (*structTextMarshalerAlias)(nil),
  12. (*struct {
  13. S string
  14. M structTextMarshaler
  15. I int8
  16. })(nil),
  17. (*struct {
  18. S string
  19. M structTextMarshalerAlias
  20. I int8
  21. })(nil),
  22. )
  23. }
  24. type structTextMarshaler struct {
  25. X string
  26. }
  27. func (m structTextMarshaler) encode(str string) string {
  28. buf := bytes.Buffer{}
  29. b64 := base64.NewEncoder(base64.StdEncoding, &buf)
  30. if _, err := b64.Write([]byte(str)); err != nil {
  31. panic(err)
  32. }
  33. if err := b64.Close(); err != nil {
  34. panic(err)
  35. }
  36. return buf.String()
  37. }
  38. func (m structTextMarshaler) decode(str string) string {
  39. if len(str) == 0 {
  40. return ""
  41. }
  42. b64 := base64.NewDecoder(base64.StdEncoding, strings.NewReader(str))
  43. bs := make([]byte, len(str))
  44. if n, err := b64.Read(bs); err != nil {
  45. panic(err)
  46. } else {
  47. bs = bs[:n]
  48. }
  49. return string(bs)
  50. }
  51. func (m structTextMarshaler) MarshalText() ([]byte, error) {
  52. return []byte(`MANUAL__` + m.encode(m.X)), nil
  53. }
  54. func (m *structTextMarshaler) UnmarshalText(text []byte) error {
  55. m.X = m.decode(strings.TrimPrefix(string(text), "MANUAL__"))
  56. return nil
  57. }
  58. var _ encoding.TextMarshaler = structTextMarshaler{}
  59. var _ encoding.TextUnmarshaler = &structTextMarshaler{}
  60. type structTextMarshalerAlias structTextMarshaler