go-mbox icon indicating copy to clipboard operation
go-mbox copied to clipboard

CreateMessage writer can return too many bytes written

Open magical opened this issue 4 years ago • 0 comments

The writer returned by CreateMessage can sometimes claim to have written more bytes than it was given. In particular, if a Write is done while there is an incomplete line buffered, the returned n will include the length of the buffered bytes as well as the provided bytes.

Here's a small program demonstrating the problem:

package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"time"

	mbox "github.com/emersion/go-mbox"
)

func main() {
	mboxWriter := mbox.NewWriter(ioutil.Discard)
	w, err := mboxWriter.CreateMessage("-", time.Time{})
	if err != nil {
		panic(err)
	}
	write(w, []byte("some text   "))
	write(w, []byte("end of line\n"))
}

func write(w io.Writer, b []byte) {
	n, err := w.Write(b)
	fmt.Printf("Write(%d bytes) wrote %d bytes\n", len(b), n)
	if err != nil {
		fmt.Println("error:", err)
	}
}

Playground: https://play.golang.org/p/uwFl_72yx0p

This prints

Write(12 bytes) wrote 12 bytes
Write(12 bytes) wrote 24 bytes

but it should print

Write(12 bytes) wrote 12 bytes
Write(12 bytes) wrote 12 bytes

magical avatar Dec 02 '19 03:12 magical