aboutsummaryrefslogtreecommitdiff
path: root/objects/object_file.go
blob: 7551193a34627c9be4eeb95688c25db6b4dc61c0 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package objects

import (
	"bufio"
	"bytes"
	"errors"
	"strconv"
)

type FileFragment struct {
	Blob ObjectId
	Size uint64
}

func (ff FileFragment) toProperties() properties {
	return properties{"blob": ff.Blob.String(), "size": strconv.FormatUint(ff.Size, 10)}
}

func (ff *FileFragment) fromProperties(p properties) error {
	blob, ok := p["blob"]
	if !ok {
		return errors.New("Field `blob` is missing")
	}

	var err error
	ff.Blob, err = ParseObjectId(blob)
	if err != nil {
		return err
	}

	size, ok := p["size"]
	if !ok {
		return errors.New("Field `size` is missing")
	}

	ff.Size, err = strconv.ParseUint(size, 10, 64)
	return err
}

func (a FileFragment) Equals(b FileFragment) bool {
	return a.Blob.Equals(b.Blob) && a.Size == b.Size
}

type File []FileFragment

func (f File) Type() ObjectType {
	return OTFile
}

func (f File) Payload() []byte {
	out := []byte{}

	for _, ff := range f {
		b, err := ff.toProperties().MarshalText()
		if err != nil {
			panic(err)
		}

		out = append(out, b...)
		out = append(out, '\n')
	}

	return out
}

func (f *File) FromPayload(payload []byte) error {
	sc := bufio.NewScanner(bytes.NewReader(payload))

	for sc.Scan() {
		line := sc.Bytes()
		if len(line) == 0 {
			continue
		}

		props := make(properties)
		if err := props.UnmarshalText(line); err != nil {
			return nil
		}

		ff := FileFragment{}
		if err := ff.fromProperties(props); err != nil {
			return err
		}

		*f = append(*f, ff)
	}

	return sc.Err()
}

func (a File) Equals(b File) bool {
	if len(a) != len(b) {
		return false
	}

	for i := range a {
		if !a[i].Equals(b[i]) {
			return false
		}
	}

	return true
}