aboutsummaryrefslogtreecommitdiffstats
path: root/formats/objfile/common.go
blob: 7389086d43aa7bbe8f934b3c2cacb0ebc6dffcc5 (plain) (blame)
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
package objfile

import (
	"errors"
	"io"
	"strconv"

	"gopkg.in/src-d/go-git.v3/core"
)

var (
	// ErrClosed is returned when the objfile Reader or Writer is already closed.
	ErrClosed = errors.New("objfile: already closed")
	// ErrHeader is returned when the objfile has an invalid header.
	ErrHeader = errors.New("objfile: invalid header")
)

type header struct {
	t    core.ObjectType
	size int64
}

func (h *header) Read(r io.Reader) error {
	t, err := h.readSlice(r, ' ')
	if err != nil {
		return err
	}

	h.t, err = core.ParseObjectType(string(t))
	if err != nil {
		return err
	}

	size, err := h.readSlice(r, 0)
	if err != nil {
		return err
	}

	h.size, err = strconv.ParseInt(string(size), 10, 64)
	if err != nil {
		return err
	}

	return nil
}

func (h *header) Write(w io.Writer) error {
	b := h.t.Bytes()
	b = append(b, ' ')
	b = append(b, []byte(strconv.FormatInt(h.size, 10))...)
	b = append(b, 0)
	_, err := w.Write(b)
	return err
}

// readSlice reads one byte at a time from r until it encounters delim or an
// error.
func (h *header) readSlice(r io.Reader, delim byte) ([]byte, error) {
	var buf [1]byte
	value := make([]byte, 0, 16)
	for {
		if n, err := r.Read(buf[:]); err != nil && (err != io.EOF || n == 0) {
			if err == io.EOF {
				return nil, ErrHeader
			}
			return nil, err
		}
		if buf[0] == delim {
			return value, nil
		}
		value = append(value, buf[0])
	}
}