blob: 5936d27303794d63f01e3b0fbe9d910e1450e8f8 [file] [log] [blame]
Rohan Agrawalc32d9932020-06-15 11:01:47 +00001/*
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
20package thrift
21
22import (
23 "bytes"
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +000024 "context"
Rohan Agrawalc32d9932020-06-15 11:01:47 +000025)
26
27// Memory buffer-based implementation of the TTransport interface.
28type TMemoryBuffer struct {
29 *bytes.Buffer
30 size int
31}
32
33type TMemoryBufferTransportFactory struct {
34 size int
35}
36
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +000037func (p *TMemoryBufferTransportFactory) GetTransport(trans TTransport) (TTransport, error) {
Rohan Agrawalc32d9932020-06-15 11:01:47 +000038 if trans != nil {
39 t, ok := trans.(*TMemoryBuffer)
40 if ok && t.size > 0 {
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +000041 return NewTMemoryBufferLen(t.size), nil
Rohan Agrawalc32d9932020-06-15 11:01:47 +000042 }
43 }
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +000044 return NewTMemoryBufferLen(p.size), nil
Rohan Agrawalc32d9932020-06-15 11:01:47 +000045}
46
47func NewTMemoryBufferTransportFactory(size int) *TMemoryBufferTransportFactory {
48 return &TMemoryBufferTransportFactory{size: size}
49}
50
51func NewTMemoryBuffer() *TMemoryBuffer {
52 return &TMemoryBuffer{Buffer: &bytes.Buffer{}, size: 0}
53}
54
55func NewTMemoryBufferLen(size int) *TMemoryBuffer {
56 buf := make([]byte, 0, size)
57 return &TMemoryBuffer{Buffer: bytes.NewBuffer(buf), size: size}
58}
59
60func (p *TMemoryBuffer) IsOpen() bool {
61 return true
62}
63
64func (p *TMemoryBuffer) Open() error {
65 return nil
66}
67
68func (p *TMemoryBuffer) Close() error {
69 p.Buffer.Reset()
70 return nil
71}
72
73// Flushing a memory buffer is a no-op
David K. Bainbridgee05cf0c2021-08-19 03:16:50 +000074func (p *TMemoryBuffer) Flush(ctx context.Context) error {
Rohan Agrawalc32d9932020-06-15 11:01:47 +000075 return nil
76}
77
78func (p *TMemoryBuffer) RemainingBytes() (num_bytes uint64) {
79 return uint64(p.Buffer.Len())
80}