summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/vincent-petithory/dataurl/dataurl.go
blob: 7a9fe67e4d62e4a6086c5f5a3ef5277458b39b28 (plain) (blame)
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package dataurl

import (
	"bytes"
	"encoding/base64"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"sort"
	"strconv"
	"strings"
)

const (
	// EncodingBase64 is base64 encoding for the data url
	EncodingBase64 = "base64"
	// EncodingASCII is ascii encoding for the data url
	EncodingASCII = "ascii"
)

func defaultMediaType() MediaType {
	return MediaType{
		"text",
		"plain",
		map[string]string{"charset": "US-ASCII"},
	}
}

// MediaType is the combination of a media type, a media subtype
// and optional parameters.
type MediaType struct {
	Type    string
	Subtype string
	Params  map[string]string
}

// ContentType returns the content type of the dataurl's data, in the form type/subtype.
func (mt *MediaType) ContentType() string {
	return fmt.Sprintf("%s/%s", mt.Type, mt.Subtype)
}

// String implements the Stringer interface.
//
// Params values are escaped with the Escape function, rather than in a quoted string.
func (mt *MediaType) String() string {
	var (
		buf  bytes.Buffer
		keys = make([]string, len(mt.Params))
		i    int
	)
	for k := range mt.Params {
		keys[i] = k
		i++
	}
	sort.Strings(keys)
	for _, k := range keys {
		v := mt.Params[k]
		fmt.Fprintf(&buf, ";%s=%s", k, EscapeString(v))
	}
	return mt.ContentType() + (&buf).String()
}

// DataURL is the combination of a MediaType describing the type of its Data.
type DataURL struct {
	MediaType
	Encoding string
	Data     []byte
}

// New returns a new DataURL initialized with data and
// a MediaType parsed from mediatype and paramPairs.
// mediatype must be of the form "type/subtype" or it will panic.
// paramPairs must have an even number of elements or it will panic.
// For more complex DataURL, initialize a DataURL struct.
// The DataURL is initialized with base64 encoding.
func New(data []byte, mediatype string, paramPairs ...string) *DataURL {
	parts := strings.Split(mediatype, "/")
	if len(parts) != 2 {
		panic("dataurl: invalid mediatype")
	}

	nParams := len(paramPairs)
	if nParams%2 != 0 {
		panic("dataurl: requires an even number of param pairs")
	}
	params := make(map[string]string)
	for i := 0; i < nParams; i += 2 {
		params[paramPairs[i]] = paramPairs[i+1]
	}

	mt := MediaType{
		parts[0],
		parts[1],
		params,
	}
	return &DataURL{
		MediaType: mt,
		Encoding:  EncodingBase64,
		Data:      data,
	}
}

// String implements the Stringer interface.
//
// Note: it doesn't guarantee the returned string is equal to
// the initial source string that was used to create this DataURL.
// The reasons for that are:
//  * Insertion of default values for MediaType that were maybe not in the initial string,
//  * Various ways to encode the MediaType parameters (quoted string or url encoded string, the latter is used),
func (du *DataURL) String() string {
	var buf bytes.Buffer
	du.WriteTo(&buf)
	return (&buf).String()
}

// WriteTo implements the WriterTo interface.
// See the note about String().
func (du *DataURL) WriteTo(w io.Writer) (n int64, err error) {
	var ni int
	ni, _ = fmt.Fprint(w, "data:")
	n += int64(ni)

	ni, _ = fmt.Fprint(w, du.MediaType.String())
	n += int64(ni)

	if du.Encoding == EncodingBase64 {
		ni, _ = fmt.Fprint(w, ";base64")
		n += int64(ni)
	}

	ni, _ = fmt.Fprint(w, ",")
	n += int64(ni)

	if du.Encoding == EncodingBase64 {
		encoder := base64.NewEncoder(base64.StdEncoding, w)
		ni, err = encoder.Write(du.Data)
		if err != nil {
			return
		}
		encoder.Close()
	} else if du.Encoding == EncodingASCII {
		ni, _ = fmt.Fprint(w, Escape(du.Data))
		n += int64(ni)
	} else {
		err = fmt.Errorf("dataurl: invalid encoding %s", du.Encoding)
		return
	}

	return
}

// UnmarshalText decodes a Data URL string and sets it to *du
func (du *DataURL) UnmarshalText(text []byte) error {
	decoded, err := DecodeString(string(text))
	if err != nil {
		return err
	}
	*du = *decoded
	return nil
}

// MarshalText writes du as a Data URL
func (du *DataURL) MarshalText() ([]byte, error) {
	buf := bytes.NewBuffer(nil)
	if _, err := du.WriteTo(buf); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

type encodedDataReader func(string) ([]byte, error)

var asciiDataReader encodedDataReader = func(s string) ([]byte, error) {
	us, err := Unescape(s)
	if err != nil {
		return nil, err
	}
	return []byte(us), nil
}

var base64DataReader encodedDataReader = func(s string) ([]byte, error) {
	data, err := base64.StdEncoding.DecodeString(s)
	if err != nil {
		return nil, err
	}
	return []byte(data), nil
}

type parser struct {
	du                  *DataURL
	l                   *lexer
	currentAttr         string
	unquoteParamVal     bool
	encodedDataReaderFn encodedDataReader
}

func (p *parser) parse() error {
	for item := range p.l.items {
		switch item.t {
		case itemError:
			return errors.New(item.String())
		case itemMediaType:
			p.du.MediaType.Type = item.val
			// Should we clear the default
			// "charset" parameter at this point?
			delete(p.du.MediaType.Params, "charset")
		case itemMediaSubType:
			p.du.MediaType.Subtype = item.val
		case itemParamAttr:
			p.currentAttr = item.val
		case itemLeftStringQuote:
			p.unquoteParamVal = true
		case itemParamVal:
			val := item.val
			if p.unquoteParamVal {
				p.unquoteParamVal = false
				us, err := strconv.Unquote("\"" + val + "\"")
				if err != nil {
					return err
				}
				val = us
			} else {
				us, err := UnescapeToString(val)
				if err != nil {
					return err
				}
				val = us
			}
			p.du.MediaType.Params[p.currentAttr] = val
		case itemBase64Enc:
			p.du.Encoding = EncodingBase64
			p.encodedDataReaderFn = base64DataReader
		case itemDataComma:
			if p.encodedDataReaderFn == nil {
				p.encodedDataReaderFn = asciiDataReader
			}
		case itemData:
			reader, err := p.encodedDataReaderFn(item.val)
			if err != nil {
				return err
			}
			p.du.Data = reader
		case itemEOF:
			if p.du.Data == nil {
				p.du.Data = []byte("")
			}
			return nil
		}
	}
	panic("EOF not found")
}

// DecodeString decodes a Data URL scheme string.
func DecodeString(s string) (*DataURL, error) {
	du := &DataURL{
		MediaType: defaultMediaType(),
		Encoding:  EncodingASCII,
	}

	parser := &parser{
		du: du,
		l:  lex(s),
	}
	if err := parser.parse(); err != nil {
		return nil, err
	}
	return du, nil
}

// Decode decodes a Data URL scheme from a io.Reader.
func Decode(r io.Reader) (*DataURL, error) {
	data, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	return DecodeString(string(data))
}

// EncodeBytes encodes the data bytes into a Data URL string, using base 64 encoding.
//
// The media type of data is detected using http.DetectContentType.
func EncodeBytes(data []byte) string {
	mt := http.DetectContentType(data)
	// http.DetectContentType may add spurious spaces between ; and a parameter.
	// The canonical way is to not have them.
	cleanedMt := strings.Replace(mt, "; ", ";", -1)

	return New(data, cleanedMt).String()
}