9// HeaderWriter helps create headers, folding to the next line when it would
10// become too large. Useful for creating Received and DKIM-Signature headers.
11type HeaderWriter struct {
17// Addf formats the string and calls Add.
18func (w *HeaderWriter) Addf(separator string, format string, args ...any) {
19 w.Add(separator, fmt.Sprintf(format, args...))
22// Add adds texts, each separated by separator. Individual elements in text are
24func (w *HeaderWriter) Add(separator string, texts ...string) {
26 w.b = &strings.Builder{}
28 for _, text := range texts {
30 if w.nonfirst && w.lineLen > 1 && w.lineLen+len(separator)+n > 78 {
31 w.b.WriteString("\r\n\t")
33 } else if w.nonfirst && separator != "" {
34 w.b.WriteString(separator)
35 w.lineLen += len(separator)
38 w.lineLen += len(text)
43// AddWrap adds data. If text is set, wrapping happens at space/tab, otherwise
44// anywhere in the buffer (e.g. for base64 data).
45func (w *HeaderWriter) AddWrap(buf []byte, text bool) {
51 if i := bytes.LastIndexAny(buf[:n], " \t"); i > 0 {
53 } else if i = bytes.IndexAny(buf, " \t"); i > 0 {
57 line, buf = buf[:n], buf[n:]
65 w.b.WriteString("\r\n\t")
71// Newline starts a new line.
72func (w *HeaderWriter) Newline() {
73 w.b.WriteString("\r\n\t")
78// String returns the header in string form, ending with \r\n.
79func (w *HeaderWriter) String() string {
80 return w.b.String() + "\r\n"