| OLD | NEW |
| (Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 package frame |
| 6 |
| 7 import ( |
| 8 "bytes" |
| 9 "encoding/binary" |
| 10 "io" |
| 11 ) |
| 12 |
| 13 // WriteFrame writes a single frame to an io.Writer. |
| 14 func WriteFrame(w io.Writer, frame []byte) (int, error) { |
| 15 var sizeBuf [binary.MaxVarintLen64]byte |
| 16 sizeBytes := binary.PutUvarint(sizeBuf[:], uint64(len(frame))) |
| 17 |
| 18 count, err := w.Write(sizeBuf[:sizeBytes]) |
| 19 if err != nil { |
| 20 return count, err |
| 21 } |
| 22 |
| 23 amount, err := w.Write(frame) |
| 24 count += amount |
| 25 if err != nil { |
| 26 return count, err |
| 27 } |
| 28 |
| 29 return count, nil |
| 30 } |
| 31 |
| 32 // Writer implements the io.Writer interface. Data written to the Writer is |
| 33 // translated into a series of frames. Each frame is spearated by a call to |
| 34 // Flush. |
| 35 // |
| 36 // Frame boundaries are created by calling Flush. Flush will always write a |
| 37 // frame, even if the frame's data size is zero. |
| 38 // |
| 39 // Data written over consecutive Write calls belongs to the same frame. It is |
| 40 // buffered until a frame boundary is created via Flush(). |
| 41 type Writer interface { |
| 42 io.Writer |
| 43 |
| 44 // Flush writes the buffered frame |
| 45 Flush() error |
| 46 } |
| 47 |
| 48 // writer implements the Writer interface by wrapping an io.Writer. |
| 49 type writer struct { |
| 50 inner io.Writer |
| 51 buf bytes.Buffer |
| 52 } |
| 53 |
| 54 // NewWriter creates a new Writer instance that data as frames to an underlying |
| 55 // io.Writer. |
| 56 func NewWriter(w io.Writer) Writer { |
| 57 return &writer{ |
| 58 inner: w, |
| 59 } |
| 60 } |
| 61 |
| 62 func (w *writer) Write(data []byte) (int, error) { |
| 63 return w.buf.Write(data) |
| 64 } |
| 65 |
| 66 func (w *writer) Flush() error { |
| 67 _, err := WriteFrame(w.inner, w.buf.Bytes()) |
| 68 if err != nil { |
| 69 return err |
| 70 } |
| 71 |
| 72 w.buf.Reset() |
| 73 return nil |
| 74 } |
| OLD | NEW |