memory_buffer.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. )
  23. // Memory buffer-based implementation of the TTransport interface.
  24. type TMemoryBuffer struct {
  25. *bytes.Buffer
  26. size int
  27. }
  28. type TMemoryBufferTransportFactory struct {
  29. size int
  30. }
  31. func (p *TMemoryBufferTransportFactory) GetTransport(trans TTransport) TTransport {
  32. if trans != nil {
  33. t, ok := trans.(*TMemoryBuffer)
  34. if ok && t.size > 0 {
  35. return NewTMemoryBufferLen(t.size)
  36. }
  37. }
  38. return NewTMemoryBufferLen(p.size)
  39. }
  40. func NewTMemoryBufferTransportFactory(size int) *TMemoryBufferTransportFactory {
  41. return &TMemoryBufferTransportFactory{size: size}
  42. }
  43. func NewTMemoryBuffer() *TMemoryBuffer {
  44. return &TMemoryBuffer{Buffer: &bytes.Buffer{}, size: 0}
  45. }
  46. func NewTMemoryBufferLen(size int) *TMemoryBuffer {
  47. buf := make([]byte, 0, size)
  48. return &TMemoryBuffer{Buffer: bytes.NewBuffer(buf), size: size}
  49. }
  50. func (p *TMemoryBuffer) IsOpen() bool {
  51. return true
  52. }
  53. func (p *TMemoryBuffer) Open() error {
  54. return nil
  55. }
  56. func (p *TMemoryBuffer) Close() error {
  57. p.Buffer.Reset()
  58. return nil
  59. }
  60. // Flushing a memory buffer is a no-op
  61. func (p *TMemoryBuffer) Flush() error {
  62. return nil
  63. }
  64. func (p *TMemoryBuffer) RemainingBytes() (num_bytes uint64) {
  65. return uint64(p.Buffer.Len())
  66. }