TMemoryBuffer.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. /*
  3. * Licensed to the Apache Software Foundation (ASF) under one
  4. * or more contributor license agreements. See the NOTICE file
  5. * distributed with this work for additional information
  6. * regarding copyright ownership. The ASF licenses this file
  7. * to you under the Apache License, Version 2.0 (the
  8. * "License"); you may not use this file except in compliance
  9. * with the License. You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing,
  14. * software distributed under the License is distributed on an
  15. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16. * KIND, either express or implied. See the License for the
  17. * specific language governing permissions and limitations
  18. * under the License.
  19. *
  20. * @package thrift.transport
  21. */
  22. namespace Thrift\Transport;
  23. use Thrift\Exception\TTransportException;
  24. use Thrift\Factory\TStringFuncFactory;
  25. /**
  26. * A memory buffer is a tranpsort that simply reads from and writes to an
  27. * in-memory string buffer. Anytime you call write on it, the data is simply
  28. * placed into a buffer, and anytime you call read, data is read from that
  29. * buffer.
  30. *
  31. * @package thrift.transport
  32. */
  33. class TMemoryBuffer extends TTransport
  34. {
  35. /**
  36. * Constructor. Optionally pass an initial value
  37. * for the buffer.
  38. */
  39. public function __construct($buf = '')
  40. {
  41. $this->buf_ = $buf;
  42. }
  43. protected $buf_ = '';
  44. public function isOpen()
  45. {
  46. return true;
  47. }
  48. public function open() {}
  49. public function close() {}
  50. public function write($buf)
  51. {
  52. $this->buf_ .= $buf;
  53. }
  54. public function read($len)
  55. {
  56. $bufLength = TStringFuncFactory::create()->strlen($this->buf_);
  57. if ($bufLength === 0) {
  58. throw new TTransportException('TMemoryBuffer: Could not read ' .
  59. $len . ' bytes from buffer.',
  60. TTransportException::UNKNOWN);
  61. }
  62. if ($bufLength <= $len) {
  63. $ret = $this->buf_;
  64. $this->buf_ = '';
  65. return $ret;
  66. }
  67. $ret = TStringFuncFactory::create()->substr($this->buf_, 0, $len);
  68. $this->buf_ = TStringFuncFactory::create()->substr($this->buf_, $len);
  69. return $ret;
  70. }
  71. public function getBuffer()
  72. {
  73. return $this->buf_;
  74. }
  75. public function available()
  76. {
  77. return TStringFuncFactory::create()->strlen($this->buf_);
  78. }
  79. public function putBack($data)
  80. {
  81. $this->buf_ = $data.$this->buf_;
  82. }
  83. }