| 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 recordio |
| 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 sizeBuf := make([]byte, binary.MaxVarintLen64) |
| 16 count, err := w.Write(sizeBuf[:binary.PutUvarint(sizeBuf, uint64(len(fra
me)))]) |
| 17 if err != nil { |
| 18 return count, err |
| 19 } |
| 20 |
| 21 amount, err := w.Write(frame) |
| 22 count += amount |
| 23 if err != nil { |
| 24 return count, err |
| 25 } |
| 26 |
| 27 return count, nil |
| 28 } |
| 29 |
| 30 // Writer implements the io.Writer interface. Data written to the Writer is |
| 31 // translated into a series of frames. Each frame is spearated by a call to |
| 32 // Flush. |
| 33 // |
| 34 // Frame boundaries are created by calling Flush. Flush will always write a |
| 35 // frame, even if the frame's data size is zero. |
| 36 // |
| 37 // Data written over consecutive Write calls belongs to the same frame. It is |
| 38 // buffered until a frame boundary is created via Flush(). |
| 39 type Writer interface { |
| 40 io.Writer |
| 41 |
| 42 // Flush writes the buffered frame |
| 43 Flush() error |
| 44 |
| 45 // Reset clears the writer state and attaches it to a new inner Writer |
| 46 // instance. |
| 47 Reset(io.Writer) |
| 48 } |
| 49 |
| 50 // writer implements the Writer interface by wrapping an io.Writer. |
| 51 type writer struct { |
| 52 inner io.Writer |
| 53 buf bytes.Buffer |
| 54 } |
| 55 |
| 56 // NewWriter creates a new Writer instance that data as frames to an underlying |
| 57 // io.Writer. |
| 58 func NewWriter(w io.Writer) Writer { |
| 59 return &writer{ |
| 60 inner: w, |
| 61 } |
| 62 } |
| 63 |
| 64 func (w *writer) Write(data []byte) (int, error) { |
| 65 return w.buf.Write(data) |
| 66 } |
| 67 |
| 68 func (w *writer) Flush() error { |
| 69 _, err := WriteFrame(w.inner, w.buf.Bytes()) |
| 70 if err != nil { |
| 71 return err |
| 72 } |
| 73 |
| 74 w.buf.Reset() |
| 75 return nil |
| 76 } |
| 77 |
| 78 func (w *writer) Reset(inner io.Writer) { |
| 79 w.inner = inner |
| 80 w.buf.Reset() |
| 81 } |
| OLD | NEW |