-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwriter.go
72 lines (64 loc) · 1.5 KB
/
writer.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
71
72
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: 2019 Gabriel Ochsenhofer
// SPDX-FileCopyrightText: 2025 TotallyGamerJet
package bsdiff
import (
"fmt"
"io"
"sync"
)
// bufWriter is byte slice buffer that implements io.WriteSeeker
type bufWriter struct {
lock sync.Mutex
buf []byte
pos int
}
var _ io.Writer = (*bufWriter)(nil)
// Write the contents of p and return the bytes written
func (m *bufWriter) Write(p []byte) (n int, err error) {
m.lock.Lock()
defer m.lock.Unlock()
if m.buf == nil {
m.buf = make([]byte, 0)
m.pos = 0
}
minCap := m.pos + len(p)
if minCap > cap(m.buf) { // Make sure buf has enough capacity:
buf2 := make([]byte, len(m.buf), minCap+len(p)) // add some extra
copy(buf2, m.buf)
m.buf = buf2
}
if minCap > len(m.buf) {
m.buf = m.buf[:minCap]
}
copy(m.buf[m.pos:], p)
m.pos += len(p)
return len(p), nil
}
// Seek to a position on the byte slice
func (m *bufWriter) Seek(offset int64, whence int) (int64, error) {
newPos, offs := 0, int(offset)
switch whence {
case io.SeekStart:
newPos = offs
case io.SeekCurrent:
newPos = m.pos + offs
case io.SeekEnd:
newPos = len(m.buf) + offs
}
if newPos < 0 {
return 0, fmt.Errorf("negative result pos")
}
m.pos = newPos
return int64(newPos), nil
}
// Len returns the length of the internal byte slice
func (m *bufWriter) Len() int {
return len(m.buf)
}
// Bytes return a copy of the internal byte slice
func (m *bufWriter) Bytes() []byte {
b2 := make([]byte, len(m.buf))
copy(b2, m.buf)
return b2
}