~samwhited/xmpp

ref: bb3bf8e486439ef6d8109b0d91cb8d2bcb3fec4b xmpp/internal/marshal/encode.go -rw-r--r-- 1.9 KiB
bb3bf8e4Sam Whited internal/marshal: use data driven testing 3 months ago
                                                                                
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
// Copyright 2019 The Mellium Contributors.
// Use of this source code is governed by the BSD 2-clause
// license that can be found in the LICENSE file.

// Package marshal contains functions for encoding structs as an XML token
// stream.
package marshal // import "mellium.im/xmpp/internal/marshal"

import (
	"bytes"
	"encoding/xml"

	"mellium.im/xmlstream"
)

// BUG(ssw): This package is very inefficient, see https://mellium.im/issue/38.

// TokenReader returns a reader for the XML encoding of v.
func TokenReader(v interface{}) (xml.TokenReader, error) {
	// If the payload to marshal is already a TokenReader, just return it.
	if r, ok := v.(xml.TokenReader); ok {
		return r, nil
	}

	var b bytes.Buffer
	err := xml.NewEncoder(&b).Encode(v)
	if err != nil {
		return nil, err
	}
	return xml.NewDecoder(&b), nil
}

// EncodeXML writes the XML encoding of v to the stream.
//
// See the documentation for xml.Marshal for details about the conversion of Go
// values to XML.
//
// If the stream is an xmlstream.Flusher, EncodeXML calls Flush before
// returning.
func EncodeXML(w xmlstream.TokenWriter, v interface{}) error {
	r, err := TokenReader(v)
	if err != nil {
		return err
	}
	_, err = xmlstream.Copy(w, r)
	if err != nil {
		return err
	}

	if wf, ok := w.(xmlstream.Flusher); ok {
		return wf.Flush()
	}
	return nil
}

// EncodeXMLElement writes the XML encoding of v to the stream, using start as
// the outermost tag in the encoding.
//
// See the documentation for xml.Marshal for details about the conversion of Go
// values to XML.
//
// If the stream is an xmlstream.Flusher, EncodeXMLElement calls Flush before
// returning.
func EncodeXMLElement(w xmlstream.TokenWriter, v interface{}, start xml.StartElement) error {
	r, err := TokenReader(v)
	if err != nil {
		return err
	}
	_, err = xmlstream.Copy(w, xmlstream.Wrap(r, start))
	if err != nil {
		return err
	}

	if wf, ok := w.(xmlstream.Flusher); ok {
		return wf.Flush()
	}
	return nil
}