splice.go 1.7 KB

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