Debian Codegraph @

splitter.go

raw symbols SCIP
1 package mailyak
2
3 import (
4 "io"
5 )
6
7 const maxLineLen = 60
8
9 // lineSplitter breaks the given input into lines of maxLineLen characters
10 // before writing a "\r\n" newline
11 type lineSplitter struct {
12 w io.Writer
13 wrote uint
14 maxLen int
15 }
16
17 type lineSplitterBuilder struct{}
18
19 func (b lineSplitterBuilder) new(w io.Writer) io.Writer {
20 return &lineSplitter{w: w, maxLen: maxLineLen}
21 }
22
23 func (w *lineSplitter) Write(p []byte) (int, error) {
24 // Calculate the previously wrote line length
25 leftover := w.wrote % uint(w.maxLen)
26
27 // Calculate the amount of bytes remaining for this line
28 lineSize := w.maxLen - int(leftover)
29
30 // Break p into chunks
31 for i := 0; i < len(p); i += lineSize {
32
33 // Reset linesize
34 if i%w.maxLen != 0 && lineSize < w.maxLen {
35 lineSize = w.maxLen
36 }
37
38 // Calculate the end of the chunk offset
39 end := i + lineSize
40 if end > len(p) {
41 end = len(p)
42 }
43
44 // Slice chunk out of p
45 chunk := p[i:end]
46 // Increment the amount wrote so far by the chunk size
47 w.wrote += uint(len(chunk))
48
49 // Write the chunk
50 if n, err := w.w.Write(chunk); err != nil {
51 return i + n, err
52 }
53
54 // If this finishes a line, add linebreaks
55 if end == i+lineSize {
56 if _, err := w.w.Write([]byte("\r\n")); err != nil {
57 // If this errors, return the bytes wrote so far from the
58 // caller's perspective (it is unaware newlines are being added)
59 return i + len(chunk), err
60 }
61 }
62 }
63
64 return len(p), nil
65 }