| 1 |
package element |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
|
| 7 |
"github.com/mitch000001/go-hbci/token" |
| 8 |
) |
| 9 |
|
| 10 |
// ExtractElements extracts DataElements from a DataElementGroup |
| 11 |
func ExtractElements(dataElementGroup []byte) ([][]byte, error) { |
| 12 |
extractor := newElementExtractor(dataElementGroup) |
| 13 |
return extractor.Extract() |
| 14 |
} |
| 15 |
|
| 16 |
// newElementExtractor creates a new GroupExtractor ready to use |
| 17 |
func newElementExtractor(dataElementGroup []byte) *groupExtractor { |
| 18 |
// TODO: workaround to get the lexer work properly for us. Maybe we should adopt the lexer? |
| 19 |
if bytes.LastIndexFunc(dataElementGroup, func(r rune) bool { |
| 20 |
return r == '+' || r == '\'' |
| 21 |
}) == -1 { |
| 22 |
dataElementGroup = append(dataElementGroup, '+') |
| 23 |
} |
| 24 |
return &groupExtractor{ |
| 25 |
rawDataElementGroup: dataElementGroup, |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
// An groupExtractor extracts DataElements from DataElementGroups |
| 30 |
type groupExtractor struct { |
| 31 |
rawDataElementGroup []byte |
| 32 |
elements [][]byte |
| 33 |
} |
| 34 |
|
| 35 |
// Extract extracts DataElements from the underlying DataElementGroup |
| 36 |
func (e *groupExtractor) Extract() ([][]byte, error) { |
| 37 |
var current []byte |
| 38 |
lexer := token.NewLexer("ElementExtractor", e.rawDataElementGroup) |
| 39 |
for lexer.HasNext() { |
| 40 |
t := lexer.Next() |
| 41 |
currentType := t.Type() |
| 42 |
if currentType == token.ERROR { |
| 43 |
return nil, fmt.Errorf("%T: SyntaxError at position %d: %q\n(%q)", e, t.Pos(), t.Value(), e.rawDataElementGroup) |
| 44 |
} |
| 45 |
if currentType == token.SEGMENT_END_MARKER || currentType == token.DATA_ELEMENT_SEPARATOR || currentType == token.GROUP_DATA_ELEMENT_SEPARATOR { |
| 46 |
e.elements = append(e.elements, current) |
| 47 |
current = []byte{} |
| 48 |
} else { |
| 49 |
current = append(current, t.Value()...) |
| 50 |
} |
| 51 |
} |
| 52 |
result := make([][]byte, len(e.elements)) |
| 53 |
copy(result, e.elements) |
| 54 |
return result, nil |
| 55 |
} |