-
Notifications
You must be signed in to change notification settings - Fork 98
/
asciiconverter.go
89 lines (73 loc) · 1.77 KB
/
asciiconverter.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
83
84
85
86
87
88
89
package ftpserver
import (
"bufio"
"io"
)
type convertMode int8
const (
convertModeToCRLF convertMode = iota
convertModeToLF
bufferSize = 4096
)
type asciiConverter struct {
reader *bufio.Reader
mode convertMode
remaining []byte
}
func newASCIIConverter(r io.Reader, mode convertMode) *asciiConverter {
reader := bufio.NewReaderSize(r, bufferSize)
return &asciiConverter{
reader: reader,
mode: mode,
remaining: nil,
}
}
func (c *asciiConverter) Read(bytes []byte) (int, error) {
var data []byte
var readBytes int
var err error
if len(c.remaining) > 0 {
data = c.remaining
c.remaining = nil
} else {
data, _, err = c.reader.ReadLine()
if err != nil {
return readBytes, err
}
}
readBytes = len(data)
if readBytes > 0 {
maxSize := len(bytes) - 2
if readBytes > maxSize {
copy(bytes, data[:maxSize])
c.remaining = data[maxSize:]
return maxSize, nil
}
copy(bytes[:readBytes], data[:readBytes])
}
// we can have a partial read if the line is too long
// or a trailing line without a line ending, so we check
// the last byte to decide if we need to add a line ending.
// This will also ensure that a file without line endings
// will remain unchanged.
// Please note that a binary file will likely contain
// newline chars so it will be still corrupted if the
// client transfers it in ASCII mode
err = c.reader.UnreadByte()
if err != nil {
return readBytes, err
}
lastByte, err := c.reader.ReadByte()
if err == nil && lastByte == '\n' {
switch c.mode {
case convertModeToCRLF:
bytes[readBytes] = '\r'
bytes[readBytes+1] = '\n'
readBytes += 2
case convertModeToLF:
bytes[readBytes] = '\n'
readBytes++
}
}
return readBytes, err //nolint:wrapcheck // here wrapping errors brings nothing
}