4 * Copyright (c) 2006- Facebook
5 * Distributed under the Thrift Software License
7 * See accompanying file LICENSE or visit the Thrift site at:
8 * http://developers.facebook.com/thrift/
10 * @package thrift.transport
11 * @author Mark Slee <mcslee@facebook.com>
15 * Buffered transport. Stores data to an internal buffer that it doesn't
16 * actually write out until flush is called. For reading, we do a greedy
17 * read and then serve data out of the internal buffer.
19 * @package thrift.transport
20 * @author Mark Slee <mcslee@facebook.com>
22 class TBufferedTransport
extends TTransport
{
25 * Constructor. Creates a buffered transport around an underlying transport
27 public function __construct($transport=null, $rBufSize=512, $wBufSize=512) {
28 $this->transport_
= $transport;
29 $this->rBufSize_
= $rBufSize;
30 $this->wBufSize_
= $wBufSize;
34 * The underlying transport
38 protected $transport_ = null;
41 * The receive buffer size
45 protected $rBufSize_ = 512;
48 * The write buffer size
52 protected $wBufSize_ = 512;
59 protected $wBuf_ = '';
66 protected $rBuf_ = '';
68 public function isOpen() {
69 return $this->transport_
->isOpen();
72 public function open() {
73 $this->transport_
->open();
76 public function close() {
77 $this->transport_
->close();
80 public function putBack($data) {
81 if (strlen($this->rBuf_
) === 0) {
84 $this->rBuf_
= ($data . $this->rBuf_
);
89 * The reason that we customize readAll here is that the majority of PHP
90 * streams are already internally buffered by PHP. The socket stream, for
91 * example, buffers internally and blocks if you call read with $len greater
92 * than the amount of data available, unlike recv() in C.
94 * Therefore, use the readAll method of the wrapped transport inside
95 * the buffered readAll.
97 public function readAll($len) {
98 $have = strlen($this->rBuf_
);
100 $data = $this->transport_
->readAll($len);
101 } else if ($have < $len) {
102 $data = $this->rBuf_
;
104 $data .= $this->transport_
->readAll($len - $have);
105 } else if ($have == $len) {
106 $data = $this->rBuf_
;
108 } else if ($have > $len) {
109 $data = substr($this->rBuf_
, 0, $len);
110 $this->rBuf_
= substr($this->rBuf_
, $len);
115 public function read($len) {
116 if (strlen($this->rBuf_
) === 0) {
117 $this->rBuf_
= $this->transport_
->read($this->rBufSize_
);
120 if (strlen($this->rBuf_
) <= $len) {
126 $ret = substr($this->rBuf_
, 0, $len);
127 $this->rBuf_
= substr($this->rBuf_
, $len);
131 public function write($buf) {
132 $this->wBuf_
.= $buf;
133 if (strlen($this->wBuf_
) >= $this->wBufSize_
) {
134 $this->transport_
->write($this->wBuf_
);
139 public function flush() {
140 if (strlen($this->wBuf_
) > 0) {
141 $this->transport_
->write($this->wBuf_
);
144 $this->transport_
->flush();