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