Elia Battiston | c8d0d46 | 2022-02-22 16:30:51 +0100 | [diff] [blame^] | 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 | |
| 20 | package thrift |
| 21 | |
| 22 | import ( |
| 23 | "bytes" |
| 24 | "context" |
| 25 | ) |
| 26 | |
| 27 | // Memory buffer-based implementation of the TTransport interface. |
| 28 | type TMemoryBuffer struct { |
| 29 | *bytes.Buffer |
| 30 | size int |
| 31 | } |
| 32 | |
| 33 | type TMemoryBufferTransportFactory struct { |
| 34 | size int |
| 35 | } |
| 36 | |
| 37 | func (p *TMemoryBufferTransportFactory) GetTransport(trans TTransport) (TTransport, error) { |
| 38 | if trans != nil { |
| 39 | t, ok := trans.(*TMemoryBuffer) |
| 40 | if ok && t.size > 0 { |
| 41 | return NewTMemoryBufferLen(t.size), nil |
| 42 | } |
| 43 | } |
| 44 | return NewTMemoryBufferLen(p.size), nil |
| 45 | } |
| 46 | |
| 47 | func NewTMemoryBufferTransportFactory(size int) *TMemoryBufferTransportFactory { |
| 48 | return &TMemoryBufferTransportFactory{size: size} |
| 49 | } |
| 50 | |
| 51 | func NewTMemoryBuffer() *TMemoryBuffer { |
| 52 | return &TMemoryBuffer{Buffer: &bytes.Buffer{}, size: 0} |
| 53 | } |
| 54 | |
| 55 | func NewTMemoryBufferLen(size int) *TMemoryBuffer { |
| 56 | buf := make([]byte, 0, size) |
| 57 | return &TMemoryBuffer{Buffer: bytes.NewBuffer(buf), size: size} |
| 58 | } |
| 59 | |
| 60 | func (p *TMemoryBuffer) IsOpen() bool { |
| 61 | return true |
| 62 | } |
| 63 | |
| 64 | func (p *TMemoryBuffer) Open() error { |
| 65 | return nil |
| 66 | } |
| 67 | |
| 68 | func (p *TMemoryBuffer) Close() error { |
| 69 | p.Buffer.Reset() |
| 70 | return nil |
| 71 | } |
| 72 | |
| 73 | // Flushing a memory buffer is a no-op |
| 74 | func (p *TMemoryBuffer) Flush(ctx context.Context) error { |
| 75 | return nil |
| 76 | } |
| 77 | |
| 78 | func (p *TMemoryBuffer) RemainingBytes() (num_bytes uint64) { |
| 79 | return uint64(p.Buffer.Len()) |
| 80 | } |