forked from balacode/go-delta
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelta_bytes.go
70 lines (66 loc) · 1.8 KB
/
delta_bytes.go
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
// -----------------------------------------------------------------------------
// github.com/balacode/go-delta go-delta/[delta_bytes.go]
// (c) [email protected] License: MIT
// -----------------------------------------------------------------------------
package delta
import (
"bytes"
"encoding/binary"
)
// Bytes converts the Delta structure to a byte array
// (for serializing to a file, etc.)
func (ob *Delta) Bytes() []byte {
buf := bytes.NewBuffer(make([]byte, 0, 1024))
//
writeInt := func(i int) error {
err := binary.Write(buf, binary.BigEndian, int32(i))
if err != nil {
return mod.Error("writeInt(", i, ") failed:", err)
}
return nil
}
writeBytes := func(data []byte) error {
err := writeInt(len(data))
if err != nil {
return mod.Error("writeBytes([", len(data), "]) failed @1:", err)
}
var n int
n, err = buf.Write(data)
if err != nil {
return mod.Error("writeBytes([", len(data), "]) failed @2:", err)
}
if n != len(data) {
return mod.Error("writeBytes([", len(data), "]) failed @3:",
"wrote wrong number of bytes:", n)
}
return nil
}
// write the header
writeInt(ob.sourceSize)
writeBytes(ob.sourceHash)
writeInt(ob.targetSize)
writeBytes(ob.targetHash)
writeInt(ob.newCount)
writeInt(ob.oldCount)
writeInt(len(ob.parts))
//
// write the parts
for _, part := range ob.parts {
writeInt(part.sourceLoc)
if part.sourceLoc == -1 {
writeBytes(part.data)
continue
}
writeInt(part.size)
}
// compress the delta
if DebugInfo {
PL("uncompressed delta length:", len(buf.Bytes()))
}
ret := compressBytes(buf.Bytes())
if DebugInfo {
PL("compressed delta length:", len(ret))
}
return ret
} // Bytes
// end