summaryrefslogtreecommitdiff
path: root/deb822/parse.go
blob: a8a02e6a73b9106e4e4238d204c7e15ceb83539b (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
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
package deb822

import (
	"bufio"
	"fmt"
	"strings"
)

/*ParseStream parses a stream and returns an array of maps, where
/* each map contains all the fields of an RFC822 stanza */
func ParseStream(stream *bufio.Scanner) (Stanzas, int) {

	s := make(Stanzas, 10)
	curSize := 10
	for i := 0; i < 10; i++ {
		s[i] = make(map[string]string)
	}
	curStanza := 0
	curField := ""
	for stream.Scan() {
		if strings.TrimSpace(stream.Text()) == "" {
			if curField == "" {
				continue
			}
			curStanza++
			curField = ""
			fmt.Printf("==== New stanza ==== (Nr. %d/%d)\n", curStanza, curSize)
			if curStanza >= curSize {
				newS := make(Stanzas, curSize*2)
				for i := curSize; i < curSize*2; i++ {
					newS[i] = make(map[string]string)
				}
				curSize *= 2
				copy(newS, s)
				s = newS
			}
			continue
		}

		//fmt.Printf("line: %s\n", stream.Text())
		field := strings.SplitN(stream.Text(), ":", 2)
		//fmt.Printf("field: %s\n", field)
		if len(field) > 1 {
			/* This is a new field*/
			curField = field[0]
			s[curStanza][curField] = strings.TrimSpace(field[1])
		} else {
			/* this is the continuation of the last field */
			s[curStanza][curField] += "\n" + field[0]
		}
	}
	return s, curStanza
}

/*ScanStanza reads a single RFC822 stanza from a stream and returns
/* it as a map */
func ScanStanza(stream *bufio.Scanner) (Stanza, error) {

	s := make(Stanza)

	curField := ""
	for stream.Scan() {
		if strings.TrimSpace(stream.Text()) == "" {
			return s, nil
		}

		field := strings.SplitN(stream.Text(), ":", 2)
		if len(field) > 1 {
			/* This is a new field*/
			curField = field[0]
			s[curField] = strings.TrimSpace(field[1])
		} else {
			/* this is the continuation of the last field */
			s[curField] += "\n" + field[0]
		}
	}

	err := stream.Err()
	return s, err
}