memory_buffer.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. package thrift
  20. import (
  21. "bytes"
  22. "context"
  23. )
  24. // Memory buffer-based implementation of the TTransport interface.
  25. type TMemoryBuffer struct {
  26. *bytes.Buffer
  27. size int
  28. }
  29. type TMemoryBufferTransportFactory struct {
  30. size int
  31. }
  32. func (p *TMemoryBufferTransportFactory) GetTransport(trans TTransport) (TTransport, error) {
  33. if trans != nil {
  34. t, ok := trans.(*TMemoryBuffer)
  35. if ok && t.size > 0 {
  36. return NewTMemoryBufferLen(t.size), nil
  37. }
  38. }
  39. return NewTMemoryBufferLen(p.size), nil
  40. }
  41. func NewTMemoryBufferTransportFactory(size int) *TMemoryBufferTransportFactory {
  42. return &TMemoryBufferTransportFactory{size: size}
  43. }
  44. func NewTMemoryBuffer() *TMemoryBuffer {
  45. return &TMemoryBuffer{Buffer: &bytes.Buffer{}, size: 0}
  46. }
  47. func NewTMemoryBufferLen(size int) *TMemoryBuffer {
  48. buf := make([]byte, 0, size)
  49. return &TMemoryBuffer{Buffer: bytes.NewBuffer(buf), size: size}
  50. }
  51. func (p *TMemoryBuffer) IsOpen() bool {
  52. return true
  53. }
  54. func (p *TMemoryBuffer) Open() error {
  55. return nil
  56. }
  57. func (p *TMemoryBuffer) Close() error {
  58. p.Buffer.Reset()
  59. return nil
  60. }
  61. // Flushing a memory buffer is a no-op
  62. func (p *TMemoryBuffer) Flush(ctx context.Context) error {
  63. return nil
  64. }
  65. func (p *TMemoryBuffer) RemainingBytes() (num_bytes uint64) {
  66. return uint64(p.Buffer.Len())
  67. }