summaryrefslogtreecommitdiff
path: root/util.go
blob: 544818ea66039ca0286b722955fb00531f54fac9 (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
// Copyright (C) 2017, 2021  Luke Shumaker <lukeshu@lukeshu.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

package libfastimport

import (
	"strconv"
	"strings"

	"github.com/pkg/errors"
)

func trimLinePrefix(line string, prefix string) string {
	if !strings.HasPrefix(line, prefix) {
		panic("line didn't have prefix")
	}
	if !strings.HasSuffix(line, "\n") {
		panic("line didn't have prefix")
	}
	return strings.TrimSuffix(strings.TrimPrefix(line, prefix), "\n")
}

func parse_data(line string) (data string, err error) {
	nl := strings.IndexByte(line, '\n')
	if nl < 0 {
		return "", errors.Errorf("data: expected newline: %q", data)
	}
	head := line[:nl+1]
	rest := line[nl+1:]
	if !strings.HasPrefix(head, "data ") {
		return "", errors.Errorf("data: could not parse: %q", data)
	}
	if strings.HasPrefix(head, "data <<") {
		// Delimited format
		delim := trimLinePrefix(head, "data <<")
		suffix := "\n" + delim + "\n"
		if !strings.HasSuffix(rest, suffix) {
			return "", errors.Errorf("data: did not find suffix: %q", suffix)
		}
		data = strings.TrimSuffix(rest, suffix)
	} else {
		// Exact byte count format
		size, err := strconv.Atoi(trimLinePrefix(head, "data "))
		if err != nil {
			return "", err
		}
		if size != len(rest) {
			panic("FIReader should not have let this happen")
		}
		data = rest
	}
	return
}