github.com/webmafia/fast@v0.10.0/binary/stream_write.go (about) 1 package binary 2 3 import ( 4 "io" 5 6 "github.com/webmafia/fast" 7 ) 8 9 var _ Writer = (*StreamWriter)(nil) 10 11 // A Stream is used to efficiently write binary data to 12 // an io.Writer. 13 type StreamWriter struct { 14 w io.Writer 15 } 16 17 func NewStreamWriter(w io.Writer) *StreamWriter { 18 return &StreamWriter{ 19 w: w, 20 } 21 } 22 23 // Reset resets the Stream to be empty. 24 func (b *StreamWriter) Reset(w io.Writer) { 25 b.w = w 26 } 27 28 // Write appends the contents of p to b's buffer. 29 // Write always returns len(p), nil. 30 // 31 //go:inline 32 func (b *StreamWriter) Write(p []byte) (int, error) { 33 return b.w.Write(fast.NoescapeBytes(p)) 34 } 35 36 // WriteByte appends the byte c to b's buffer. 37 // The returned error is always nil. 38 func (b *StreamWriter) WriteByte(c byte) (err error) { 39 _, err = b.Write([]byte{c}) 40 return 41 } 42 43 // WriteString appends the contents of s to b's buffer. 44 // It returns the length of s and a nil error. 45 func (b *StreamWriter) WriteString(s string) (int, error) { 46 return b.Write(fast.StringToBytes(s)) 47 } 48 49 func (b *StreamWriter) WriteVal(val any) error { 50 switch v := val.(type) { 51 52 case Encoder: 53 return b.WriteEnc(v) 54 55 case string: 56 _, err := b.WriteString(v) 57 return err 58 59 case []byte: 60 _, err := b.Write(v) 61 return err 62 63 case int: 64 return b.WriteInt(v) 65 66 case int8: 67 return b.WriteInt8(v) 68 69 case int16: 70 return b.WriteInt16(v) 71 72 case int32: 73 return b.WriteInt32(v) 74 75 case int64: 76 return b.WriteInt64(v) 77 78 case uint: 79 return b.WriteUint(v) 80 81 case uint8: 82 return b.WriteUint8(v) 83 84 case uint16: 85 return b.WriteUint16(v) 86 87 case uint32: 88 return b.WriteUint32(v) 89 90 case uint64: 91 return b.WriteUint64(v) 92 93 case float32: 94 return b.WriteFloat32(v) 95 96 case float64: 97 return b.WriteFloat64(v) 98 99 case bool: 100 return b.WriteBool(v) 101 102 } 103 104 return ErrUnknownValue 105 } 106 107 // Write a type that implements StringEncoder 108 func (b *StreamWriter) WriteEnc(v Encoder) error { 109 return v.Encode(b) 110 }