File: element_extractor.go

package info (click to toggle)
golang-github-mitch000001-go-hbci 0.4.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 2,468 kB
  • sloc: java: 1,092; makefile: 5
file content (55 lines) | stat: -rw-r--r-- 1,714 bytes parent folder | download | duplicates (2)
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
package element

import (
	"bytes"
	"fmt"

	"github.com/mitch000001/go-hbci/token"
)

// ExtractElements extracts DataElements from a DataElementGroup
func ExtractElements(dataElementGroup []byte) ([][]byte, error) {
	extractor := newElementExtractor(dataElementGroup)
	return extractor.Extract()
}

// newElementExtractor creates a new GroupExtractor ready to use
func newElementExtractor(dataElementGroup []byte) *groupExtractor {
	// TODO: workaround to get the lexer work properly for us. Maybe we should adopt the lexer?
	if bytes.LastIndexFunc(dataElementGroup, func(r rune) bool {
		return r == '+' || r == '\''
	}) == -1 {
		dataElementGroup = append(dataElementGroup, '+')
	}
	return &groupExtractor{
		rawDataElementGroup: dataElementGroup,
	}
}

// An groupExtractor extracts DataElements from DataElementGroups
type groupExtractor struct {
	rawDataElementGroup []byte
	elements            [][]byte
}

// Extract extracts DataElements from the underlying DataElementGroup
func (e *groupExtractor) Extract() ([][]byte, error) {
	var current []byte
	lexer := token.NewLexer("ElementExtractor", e.rawDataElementGroup)
	for lexer.HasNext() {
		t := lexer.Next()
		currentType := t.Type()
		if currentType == token.ERROR {
			return nil, fmt.Errorf("%T: SyntaxError at position %d: %q\n(%q)", e, t.Pos(), t.Value(), e.rawDataElementGroup)
		}
		if currentType == token.SEGMENT_END_MARKER || currentType == token.DATA_ELEMENT_SEPARATOR || currentType == token.GROUP_DATA_ELEMENT_SEPARATOR {
			e.elements = append(e.elements, current)
			current = []byte{}
		} else {
			current = append(current, t.Value()...)
		}
	}
	result := make([][]byte, len(e.elements))
	copy(result, e.elements)
	return result, nil
}