summaryrefslogtreecommitdiff
path: root/xmpp/routing.go
blob: c691af38f2c4f9704d2728bf7babb8148a350299 (plain)
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
package xmpp

import (
	"encoding/xml"
	"errors"
	"log"
)

type tokenRouter struct {
	start        xml.StartElement
	end          xml.EndElement
	buffer       []xml.Token
	level        uint16 // XML nesting level
	enc          *encoder
}

func newTokenRouter(e *encoder) tokenRouter {
	return tokenRouter{
		buffer: make([]xml.Token, 0),
		level:  0,
		enc:    e,
	}
}

func (r *tokenRouter) route(t xml.Token) error {
	r.buffer = append(r.buffer, t)

	switch unwrapped := t.(type) {
	case xml.StartElement:
		r.level += 1
		if r.level == 1 {
			r.start = unwrapped
			r.buffer = r.buffer[:0]
			// call start handler
		}
	case xml.EndElement:
		if r.level == 0 {
			log.Println("Ignoring XML end element on nesting level zero")
			return nil
		}
		r.level -= 1
		switch r.level {
		case 0:
			return errors.New("Stream was closed by server")
		case 1:
			// call elementRouter
			r.buffer = r.buffer[:1]
		}
	}

	return nil
}