File: writer_at.go

package info (click to toggle)
golang-github-viant-toolbox 0.33.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 1,280 kB
  • sloc: makefile: 16
file content (51 lines) | stat: -rw-r--r-- 1,119 bytes parent folder | download | duplicates (2)
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
package toolbox

import (
	"sync"
)

//ByteWriterAt  represents a bytes writer at
type ByteWriterAt struct {
	mutex    *sync.Mutex
	Buffer   []byte
	position int
}

//WriteAt returns number of written bytes or error
func (w *ByteWriterAt) WriteAt(p []byte, offset int64) (n int, err error) {
	w.mutex.Lock()

	if int(offset) == w.position {
		w.Buffer = append(w.Buffer, p...)
		w.position += len(p)
		w.mutex.Unlock()
		return len(p), nil
	} else if w.position < int(offset) {
		var diff = (int(offset) - w.position)
		var fillingBytes = make([]byte, diff)
		w.position += len(fillingBytes)
		w.Buffer = append(w.Buffer, fillingBytes...)
		w.mutex.Unlock()
		return w.WriteAt(p, offset)
	} else {
		for i := 0; i < len(p); i++ {
			var index = int(offset) + i
			if index < len(w.Buffer) {
				w.Buffer[int(offset)+i] = p[i]
			} else {
				w.Buffer = append(w.Buffer, p[i:]...)
				break
			}
		}
		w.mutex.Unlock()
		return len(p), nil
	}
}

//NewWriterAt returns a new instance of byte writer at
func NewByteWriterAt() *ByteWriterAt {
	return &ByteWriterAt{
		mutex:  &sync.Mutex{},
		Buffer: make([]byte, 0),
	}
}