]> Cypherpunks repositories - gostls13.git/commitdiff
io.WriteString: if the object has a WriteString method, use it
authorEvan Shaw <chickencha@gmail.com>
Tue, 28 Jun 2011 06:10:39 +0000 (16:10 +1000)
committerRob Pike <r@golang.org>
Tue, 28 Jun 2011 06:10:39 +0000 (16:10 +1000)
This avoids allocation when writing to bytes.Buffers and bufio.Writers, for
example.

R=golang-dev, rsc, r, consalus, r
CC=golang-dev
https://golang.org/cl/4625068

src/pkg/io/io.go

index 790cf94e7cd256b89aacc889bff4aed342bedf72..b879fe5b7213ad1a34e04c5a0ffa44e9aa0a0e99 100644 (file)
@@ -209,8 +209,16 @@ type RuneScanner interface {
        UnreadRune() os.Error
 }
 
+// stringWriter is the interface that wraps the WriteString method.
+type stringWriter interface {
+       WriteString(s string) (n int, err os.Error)
+}
+
 // WriteString writes the contents of the string s to w, which accepts an array of bytes.
 func WriteString(w Writer, s string) (n int, err os.Error) {
+       if sw, ok := w.(stringWriter); ok {
+               return sw.WriteString(s)
+       }
        return w.Write([]byte(s))
 }