blob: 2913d32aa69c55fb614f3957e5be2b30f839c333 [file] [log] [blame]
Mark Slee052bbef2010-10-11 21:45:13 +00001<?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.protocol
21 * @author: rmarin (marin.radu@facebook.com)
22 */
23
24require_once $GLOBALS['THRIFT_ROOT'].'/transport/TMemoryBuffer.php';
25require_once $GLOBALS['THRIFT_ROOT'].'/protocol/TBinaryProtocol.php';
26
27/**
28 * Utility class for serializing and deserializing
29 * a thrift object using TBinaryProtocolAccelerated.
30 */
31class TBinarySerializer {
32
33 // NOTE(rmarin): Because thrift_protocol_write_binary
34 // adds a begin message prefix, you cannot specify
35 // a transport in which to serialize an object. It has to
36 // be a string. Otherwise we will break the compatibility with
37 // normal deserialization.
38 public static function serialize($object) {
39 $transport = new TMemoryBuffer();
40 $protocol = new TBinaryProtocolAccelerated($transport);
41 if (function_exists('thrift_protocol_write_binary')) {
42 thrift_protocol_write_binary($protocol, $object->getName(),
43 TMessageType::REPLY, $object,
44 0, $protocol->isStrictWrite());
45
46 $protocol->readMessageBegin($unused_name, $unused_type,
47 $unused_seqid);
48 } else {
49 $object->write($protocol);
50 }
51 return $transport->getBuffer();
52 }
53
54 public static function deserialize($string_object, $class_name) {
55 $transport = new TMemoryBuffer();
56 $protocol = new TBinaryProtocolAccelerated($transport);
57 if (function_exists('thrift_protocol_read_binary')) {
58 $protocol->writeMessageBegin('', TMessageType::REPLY, 0);
59 $transport->write($string_object);
60 return thrift_protocol_read_binary($protocol, $class_name,
61 $protocol->isStrictRead());
62 } else {
63 $transport->write($string_object);
64 $object = new $class_name();
65 $object->read($protocol);
66 return $object;
67 }
68 }
69}