-
Notifications
You must be signed in to change notification settings - Fork 798
/
section_writer.go
53 lines (41 loc) · 958 Bytes
/
section_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
//go:build go1.18
// +build go1.18
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
package shared
import (
"errors"
"io"
)
type SectionWriter struct {
Count int64
Offset int64
Position int64
WriterAt io.WriterAt
}
func NewSectionWriter(c io.WriterAt, off int64, count int64) *SectionWriter {
return &SectionWriter{
Count: count,
Offset: off,
WriterAt: c,
}
}
func (c *SectionWriter) Write(p []byte) (int, error) {
remaining := c.Count - c.Position
if remaining <= 0 {
return 0, errors.New("end of section reached")
}
slice := p
if int64(len(slice)) > remaining {
slice = slice[:remaining]
}
n, err := c.WriterAt.WriteAt(slice, c.Offset+c.Position)
c.Position += int64(n)
if err != nil {
return n, err
}
if len(p) > n {
return n, errors.New("not enough space for all bytes")
}
return n, nil
}