File: adapters.go

package info (click to toggle)
golang-github-bep-tmc 0.5.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 108 kB
  • sloc: makefile: 2
file content (146 lines) | stat: -rw-r--r-- 3,500 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// Copyright © 2019 Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

package tmc

import (
	"encoding"
	"fmt"
	"math/big"
	"reflect"
	"strconv"
	"time"
)

// Adapter wraps a type to preserve type information when encoding and decoding
// a map.
//
// The simples way to create new adapters is via the NewAdapter function.
type Adapter interface {
	FromString(s string) (interface{}, error)
	MarshalText() (text []byte, err error)
	Type() reflect.Type
	Wrap(v interface{}) Adapter
}

var (
	// DefaultTypeAdapters contains the default set of type adapters.
	DefaultTypeAdapters = []Adapter{
		// Time
		NewAdapter(time.Now(), nil, nil),
		NewAdapter(
			3*time.Hour,
			func(s string) (interface{}, error) { return time.ParseDuration(s) },
			func(v interface{}) (string, error) { return v.(time.Duration).String(), nil },
		),

		// Numbers
		NewAdapter(big.NewRat(1, 2), nil, nil),
		NewAdapter(
			int(32),
			func(s string) (interface{}, error) {
				return strconv.Atoi(s)
			},
			func(v interface{}) (string, error) {
				return strconv.Itoa(v.(int)), nil
			},
		),
	}
)

// NewAdapter creates a new adapter that wraps the target type.
//
// fromString can be omitted if target implements encoding.TextUnmarshaler.
// toString can be omitted if target implements encoding.TextMarshaler.
//
// It will panic if it can not be created.
func NewAdapter(
	target interface{},
	fromString func(s string) (interface{}, error),
	toString func(v interface{}) (string, error)) Adapter {

	targetValue := reflect.ValueOf(target)
	targetType := targetValue.Type()

	wasPointer := targetType.Kind() == reflect.Ptr
	if !wasPointer {
		// Need the pointer to see the TextUnmarshaler implementation.
		v := targetValue
		targetValue = reflect.New(targetType)
		targetValue.Elem().Set(v)
	}

	if fromString == nil {
		if _, ok := targetValue.Interface().(encoding.TextUnmarshaler); ok {
			fromString = func(s string) (interface{}, error) {
				typ := targetType
				if typ.Kind() == reflect.Ptr {
					typ = typ.Elem()
				}
				v := reflect.New(typ)

				err := v.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(s))
				if err != nil {
					return nil, err
				}

				if !wasPointer {
					v = v.Elem()
				}
				return v.Interface(), nil
			}
		} else {
			panic(fmt.Sprintf("%T can not be unmarshaled", target))
		}
	}

	var marshalText func(v interface{}) ([]byte, error)

	if toString != nil {
		marshalText = func(v interface{}) ([]byte, error) {
			s, err := toString(v)
			return []byte(s), err
		}
	} else if _, ok := target.(encoding.TextMarshaler); ok {
		marshalText = func(v interface{}) ([]byte, error) {
			return v.(encoding.TextMarshaler).MarshalText()
		}
	} else {
		panic(fmt.Sprintf("%T can not be marshaled", target))
	}

	return &adapter{
		targetType:  targetType,
		fromString:  fromString,
		marshalText: marshalText,
	}
}

var _ Adapter = (*adapter)(nil)

type adapter struct {
	fromString  func(s string) (interface{}, error)
	marshalText func(v interface{}) (text []byte, err error)
	targetType  reflect.Type

	target interface{}
}

func (a *adapter) FromString(s string) (interface{}, error) {
	return a.fromString(s)
}

func (a *adapter) MarshalText() (text []byte, err error) {
	return a.marshalText(a.target)
}

func (a adapter) Type() reflect.Type {
	return a.targetType
}

func (a adapter) Wrap(v interface{}) Adapter {
	a.target = v
	return &a
}