1 /* 2 Copyright 2023 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package runtime 18 19 import ( 20 "bytes" 21 "io" 22 ) 23 24 // Splice is the interface that wraps the Splice method. 25 // 26 // Splice moves data from given slice without copying the underlying data for 27 // efficiency purpose. Therefore, the caller should make sure the underlying 28 // data is not changed later. 29 type Splice interface { 30 Splice([]byte) 31 io.Writer 32 Reset() 33 Bytes() []byte 34 } 35 36 // A spliceBuffer implements Splice and io.Writer interfaces. 37 type spliceBuffer struct { 38 raw []byte 39 buf *bytes.Buffer 40 } 41 42 func NewSpliceBuffer() Splice { 43 return &spliceBuffer{} 44 } 45 46 // Splice implements the Splice interface. 47 func (sb *spliceBuffer) Splice(raw []byte) { 48 sb.raw = raw 49 } 50 51 // Write implements the io.Writer interface. 52 func (sb *spliceBuffer) Write(p []byte) (n int, err error) { 53 if sb.buf == nil { 54 sb.buf = &bytes.Buffer{} 55 } 56 return sb.buf.Write(p) 57 } 58 59 // Reset resets the buffer to be empty. 60 func (sb *spliceBuffer) Reset() { 61 if sb.buf != nil { 62 sb.buf.Reset() 63 } 64 sb.raw = nil 65 } 66 67 // Bytes returns the data held by the buffer. 68 func (sb *spliceBuffer) Bytes() []byte { 69 if sb.buf != nil && len(sb.buf.Bytes()) > 0 { 70 return sb.buf.Bytes() 71 } 72 if sb.raw != nil { 73 return sb.raw 74 } 75 return []byte{} 76 } 77