text_marshaler_string_test.go 1.2 KB

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