forked from djimenez/iconv-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
82 lines (63 loc) · 1.78 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
73
74
75
76
77
78
79
80
81
82
package iconv
import "io"
type Writer struct {
destination io.Writer
converter *Converter
buffer []byte
readPos, writePos int
err error
}
func NewWriter(destination io.Writer, fromEncoding string, toEncoding string) (*Writer, error) {
// create a converter
converter, err := NewConverter(fromEncoding, toEncoding)
if err == nil {
return NewWriterFromConverter(destination, converter), err
}
// return the error
return nil, err
}
func NewWriterFromConverter(destination io.Writer, converter *Converter) (writer *Writer) {
writer = new(Writer)
// copy elements
writer.destination = destination
writer.converter = converter
// create 8K buffers
writer.buffer = make([]byte, 8*1024)
return writer
}
func (this *Writer) emptyBuffer() {
// write new data out of buffer
bytesWritten, err := this.destination.Write(this.buffer[this.readPos:this.writePos])
// update read position
this.readPos += bytesWritten
// slide existing data to beginning
if this.readPos > 0 {
// copy current bytes - is this guaranteed safe?
copy(this.buffer, this.buffer[this.readPos:this.writePos])
// adjust positions
this.writePos -= this.readPos
this.readPos = 0
}
// track any reader error / EOF
if err != nil {
this.err = err
}
}
// implement the io.Writer interface
func (this *Writer) Write(p []byte) (n int, err error) {
// write data into our internal buffer
bytesRead, bytesWritten, err := this.converter.Convert(p, this.buffer[this.writePos:])
// update bytes written for return
n += bytesRead
this.writePos += bytesWritten
// checks for when we have a full buffer
for this.writePos > 0 {
// if we have an error, just return it
if this.err != nil {
return
}
// else empty the buffer
this.emptyBuffer()
}
return n, err
}