]> Cypherpunks repositories - gostls13.git/commitdiff
WriteString
authorRob Pike <r@golang.org>
Tue, 4 Aug 2009 01:28:05 +0000 (18:28 -0700)
committerRob Pike <r@golang.org>
Tue, 4 Aug 2009 01:28:05 +0000 (18:28 -0700)
R=rsc
DELTA=41  (41 added, 0 deleted, 0 changed)
OCL=32692
CL=32697

src/pkg/bufio/bufio.go
src/pkg/bufio/bufio_test.go

index 7e4df4ef5c44227903d9b7a990d20fc8e7eaa7f3..5ef1b69e9d9f6a518f7c720e2f9c6b2e67001c56 100644 (file)
@@ -487,6 +487,25 @@ func (b *Writer) WriteByte(c byte) os.Error {
        return nil
 }
 
+// WriteString writes a string.
+func (b *Writer) WriteString(s string) os.Error {
+       if b.err != nil {
+               return b.err
+       }
+       // Common case, worth making fast.
+       if b.Available() >= len(s) || len(b.buf) >= len(s) && b.Flush() == nil {
+               for i := 0; i < len(s); i++ {   // loop over bytes, not runes.
+                       b.buf[b.n] = s[i];
+                       b.n++;
+               }
+               return nil;
+       }
+       for i := 0; i < len(s); i++ {   // loop over bytes, not runes.
+               b.WriteByte(s[i]);
+       }
+       return b.err
+}
+
 // buffered input and output
 
 // ReadWriter stores pointers to a Reader and a Writer.
index 9aab2672920b7ffe91d6bc4bbf948e4bc09f6dc7..ec7f949725c0f3341291d7acfa0d9ea59d5c1124 100644 (file)
@@ -298,3 +298,25 @@ func TestNewWriterSizeIdempotent(t *testing.T) {
                t.Error("NewWriterSize did not enlarge buffer");
        }
 }
+
+func TestWriteString(t *testing.T) {
+       const BufSize = 8;
+       buf := new(bytes.Buffer);
+       b, err := NewWriterSize(buf, BufSize);
+       if err != nil {
+               t.Error("NewWriterSize create fail", err);
+       }
+       b.WriteString("0");     // easy
+       b.WriteString("123456");        // still easy
+       b.WriteString("7890");  // easy after flush
+       b.WriteString("abcdefghijklmnopqrstuvwxy");     // hard
+       b.WriteString("z");
+       b.Flush();
+       if b.err != nil {
+               t.Error("WriteString", b.err);
+       }
+       s := "01234567890abcdefghijklmnopqrstuvwxyz";
+       if string(buf.Data()) != s {
+               t.Errorf("WriteString wants %q gets %q", s, string(buf.Data()))
+       }
+}