| 1 |
package swift |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"fmt" |
| 6 |
|
| 7 |
"github.com/mitch000001/go-hbci/charset" |
| 8 |
"github.com/mitch000001/go-hbci/token" |
| 9 |
) |
| 10 |
|
| 11 |
type rawTag struct { |
| 12 |
ID string |
| 13 |
Value []byte |
| 14 |
} |
| 15 |
|
| 16 |
func extractRawTag(tag []byte) (*rawTag, error) { |
| 17 |
elements, err := extractTagElements(tag) |
| 18 |
if err != nil { |
| 19 |
return nil, err |
| 20 |
} |
| 21 |
if len(elements) != 2 { |
| 22 |
return nil, fmt.Errorf("Malformed marshaled tag") |
| 23 |
} |
| 24 |
return &rawTag{ |
| 25 |
ID: charset.ToUTF8(elements[0]), |
| 26 |
Value: elements[1], |
| 27 |
}, nil |
| 28 |
} |
| 29 |
|
| 30 |
func extractTagElements(tag []byte) ([][]byte, error) { |
| 31 |
buf := bytes.NewBuffer(tag) |
| 32 |
b, err := buf.ReadByte() |
| 33 |
if err != nil { |
| 34 |
return nil, err |
| 35 |
} |
| 36 |
if b != ':' { |
| 37 |
return nil, fmt.Errorf("Malformed tag id") |
| 38 |
} |
| 39 |
tagBytes := make([]byte, 1) |
| 40 |
tagBytes[0] = b |
| 41 |
tagID, err := buf.ReadBytes(':') |
| 42 |
if err != nil { |
| 43 |
return nil, err |
| 44 |
} |
| 45 |
tagBytes = append(tagBytes, tagID...) |
| 46 |
tagValue := buf.Bytes() |
| 47 |
return [][]byte{ |
| 48 |
tagBytes, |
| 49 |
tagValue, |
| 50 |
}, nil |
| 51 |
} |
| 52 |
|
| 53 |
func extractTagID(tag []byte) ([]byte, error) { |
| 54 |
elements, err := extractTagElements(tag) |
| 55 |
if err != nil { |
| 56 |
return nil, err |
| 57 |
} |
| 58 |
return elements[0], nil |
| 59 |
} |
| 60 |
|
| 61 |
func newTagExtractor(swiftMessage []byte) *tagExtractor { |
| 62 |
lexer := token.NewSwiftLexer("TagExtractor", swiftMessage) |
| 63 |
return &tagExtractor{ |
| 64 |
lexer: lexer, |
| 65 |
rawSwiftMessage: swiftMessage, |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
type tagExtractor struct { |
| 70 |
lexer *token.SwiftLexer |
| 71 |
rawSwiftMessage []byte |
| 72 |
extractedTags [][]byte |
| 73 |
} |
| 74 |
|
| 75 |
func (t *tagExtractor) Extract() ([][]byte, error) { |
| 76 |
var current []byte |
| 77 |
for t.lexer.HasNext() { |
| 78 |
tok := t.lexer.Next() |
| 79 |
if tok.Type() == token.ERROR { |
| 80 |
return nil, fmt.Errorf("%T: SyntaxError at position %d: %q\n(%q)", t, tok.Pos(), tok.Value(), t.rawSwiftMessage) |
| 81 |
} |
| 82 |
if tok.Type() == token.SWIFT_TAG_SEPARATOR || tok.Type() == token.SWIFT_MESSAGE_SEPARATOR { |
| 83 |
t.extractedTags = append(t.extractedTags, current) |
| 84 |
current = []byte{} |
| 85 |
} else { |
| 86 |
if tok.Type() != token.SWIFT_DATASET_START { |
| 87 |
current = append(current, tok.Value()...) |
| 88 |
} |
| 89 |
} |
| 90 |
} |
| 91 |
result := make([][]byte, len(t.extractedTags)) |
| 92 |
copy(result, t.extractedTags) |
| 93 |
return result, nil |
| 94 |
} |