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
11 * http://www.apache.org/licenses/LICENSE-2.0
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
20 * @package thrift.protocol
21 * @author: rmarin (marin.radu@facebook.com)
24 namespace Thrift\Serializer
;
26 use Thrift\Transport\TMemoryBuffer
;
27 use Thrift\Protocol\TBinaryProtocolAccelerated
;
28 use Thrift\Type\TMessageType
;
31 * Utility class for serializing and deserializing
32 * a thrift object using TBinaryProtocolAccelerated.
34 class TBinarySerializer
36 // NOTE(rmarin): Because thrift_protocol_write_binary
37 // adds a begin message prefix, you cannot specify
38 // a transport in which to serialize an object. It has to
39 // be a string. Otherwise we will break the compatibility with
40 // normal deserialization.
41 public static function serialize($object)
43 $transport = new TMemoryBuffer();
44 $protocol = new TBinaryProtocolAccelerated($transport);
45 if (function_exists('thrift_protocol_write_binary')) {
46 thrift_protocol_write_binary(
52 $protocol->isStrictWrite()
55 $protocol->readMessageBegin($unused_name, $unused_type, $unused_seqid);
57 $object->write($protocol);
59 $protocol->getTransport()->flush();
61 return $transport->getBuffer();
64 public static function deserialize($string_object, $class_name, $buffer_size = 8192)
66 $transport = new TMemoryBuffer();
67 $protocol = new TBinaryProtocolAccelerated($transport);
68 if (function_exists('thrift_protocol_read_binary')) {
69 // NOTE (t.heintz) TBinaryProtocolAccelerated internally wraps our TMemoryBuffer in a
70 // TBufferedTransport, so we have to retrieve it again or risk losing data when writing
71 // less than 512 bytes to the transport (see the comment there as well).
73 $protocol->writeMessageBegin('', TMessageType
::REPLY
, 0);
74 $protocolTransport = $protocol->getTransport();
75 $protocolTransport->write($string_object);
76 $protocolTransport->flush();
78 return thrift_protocol_read_binary($protocol, $class_name, $protocol->isStrictRead(), $buffer_size);
80 $transport->write($string_object);
81 $object = new $class_name();
82 $object->read($protocol);