protolib.py revision 13540
113819Sgabeblack@google.com#!/usr/bin/env python2.7
213819Sgabeblack@google.com
313819Sgabeblack@google.com# Copyright (c) 2013 ARM Limited
413819Sgabeblack@google.com# All rights reserved
513819Sgabeblack@google.com#
613819Sgabeblack@google.com# The license below extends only to copyright in the software and shall
713819Sgabeblack@google.com# not be construed as granting a license to any other intellectual
813819Sgabeblack@google.com# property including but not limited to intellectual property relating
913819Sgabeblack@google.com# to a hardware implementation of the functionality of the software
1013819Sgabeblack@google.com# licensed hereunder.  You may use the software subject to the license
1113819Sgabeblack@google.com# terms below provided that you ensure that this notice is replicated
1213819Sgabeblack@google.com# unmodified and in its entirety in all distributions of the software,
1313819Sgabeblack@google.com# modified or unmodified, in source code or in binary form.
1413819Sgabeblack@google.com#
1513819Sgabeblack@google.com# Redistribution and use in source and binary forms, with or without
1613819Sgabeblack@google.com# modification, are permitted provided that the following conditions are
1713819Sgabeblack@google.com# met: redistributions of source code must retain the above copyright
1813819Sgabeblack@google.com# notice, this list of conditions and the following disclaimer;
1913819Sgabeblack@google.com# redistributions in binary form must reproduce the above copyright
2013819Sgabeblack@google.com# notice, this list of conditions and the following disclaimer in the
2113819Sgabeblack@google.com# documentation and/or other materials provided with the distribution;
2213819Sgabeblack@google.com# neither the name of the copyright holders nor the names of its
2313819Sgabeblack@google.com# contributors may be used to endorse or promote products derived from
2413819Sgabeblack@google.com# this software without specific prior written permission.
2513819Sgabeblack@google.com#
2613819Sgabeblack@google.com# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2713819Sgabeblack@google.com# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2813819Sgabeblack@google.com# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2913819Sgabeblack@google.com# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
3013819Sgabeblack@google.com# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3113819Sgabeblack@google.com# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3213819Sgabeblack@google.com# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3313819Sgabeblack@google.com# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3413819Sgabeblack@google.com# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3513819Sgabeblack@google.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3613819Sgabeblack@google.com# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3713819Sgabeblack@google.com#
3813819Sgabeblack@google.com# Copyright 2008 Google Inc.  All rights reserved.
3913819Sgabeblack@google.com# http://code.google.com/p/protobuf/
4013819Sgabeblack@google.com#
4113819Sgabeblack@google.com# Redistribution and use in source and binary forms, with or without
4213819Sgabeblack@google.com# modification, are permitted provided that the following conditions are
4313819Sgabeblack@google.com# met:
4413819Sgabeblack@google.com#
4513819Sgabeblack@google.com#     * Redistributions of source code must retain the above copyright
4613819Sgabeblack@google.com# notice, this list of conditions and the following disclaimer.
4713819Sgabeblack@google.com#     * Redistributions in binary form must reproduce the above
4813819Sgabeblack@google.com# copyright notice, this list of conditions and the following disclaimer
4913819Sgabeblack@google.com# in the documentation and/or other materials provided with the
5013819Sgabeblack@google.com# distribution.
5113819Sgabeblack@google.com#     * Neither the name of Google Inc. nor the names of its
5213819Sgabeblack@google.com# contributors may be used to endorse or promote products derived from
5313819Sgabeblack@google.com# this software without specific prior written permission.
5413819Sgabeblack@google.com#
5513819Sgabeblack@google.com# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5613819Sgabeblack@google.com# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5713819Sgabeblack@google.com# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5813819Sgabeblack@google.com# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5913819Sgabeblack@google.com# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6013819Sgabeblack@google.com# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6113819Sgabeblack@google.com# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6213819Sgabeblack@google.com# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6313819Sgabeblack@google.com# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6413819Sgabeblack@google.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6513819Sgabeblack@google.com# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6613819Sgabeblack@google.com#
6713819Sgabeblack@google.com# Authors: Andreas Hansson
6813819Sgabeblack@google.com#          Radhika Jagtap
6913819Sgabeblack@google.com
7013819Sgabeblack@google.com# This file is a library of commonly used functions used when interfacing
7113819Sgabeblack@google.com# with protobuf python messages. For eg, the decode scripts for different
7213819Sgabeblack@google.com# types of proto objects can use the same function to decode a single message
7313819Sgabeblack@google.com
7413819Sgabeblack@google.comimport gzip
7513819Sgabeblack@google.comimport struct
7613819Sgabeblack@google.com
7713819Sgabeblack@google.comdef openFileRd(in_file):
7813819Sgabeblack@google.com    """
7913819Sgabeblack@google.com    This opens the file passed as argument for reading using an appropriate
8013819Sgabeblack@google.com    function depending on if it is gzipped or not. It returns the file
8113819Sgabeblack@google.com    handle.
8213819Sgabeblack@google.com    """
8313819Sgabeblack@google.com    try:
8413819Sgabeblack@google.com        # First see if this file is gzipped
8513819Sgabeblack@google.com        try:
8613819Sgabeblack@google.com            # Opening the file works even if it is not a gzip file
8713819Sgabeblack@google.com            proto_in = gzip.open(in_file, 'rb')
8813819Sgabeblack@google.com
8913819Sgabeblack@google.com            # Force a check of the magic number by seeking in the
9013819Sgabeblack@google.com            # file. If we do not do it here the error will occur when
9113819Sgabeblack@google.com            # reading the first message.
9213819Sgabeblack@google.com            proto_in.seek(1)
9313819Sgabeblack@google.com            proto_in.seek(0)
9413819Sgabeblack@google.com        except IOError:
9513819Sgabeblack@google.com            proto_in = open(in_file, 'rb')
9613819Sgabeblack@google.com    except IOError:
9713819Sgabeblack@google.com        print "Failed to open ", in_file, " for reading"
9813819Sgabeblack@google.com        exit(-1)
9913819Sgabeblack@google.com    return proto_in
10013819Sgabeblack@google.com
10113819Sgabeblack@google.comdef _DecodeVarint32(in_file):
10213819Sgabeblack@google.com    """
10313819Sgabeblack@google.com    The decoding of the Varint32 is copied from
10413819Sgabeblack@google.com    google.protobuf.internal.decoder and is only repeated here to
10513819Sgabeblack@google.com    avoid depending on the internal functions in the library. If the
10613819Sgabeblack@google.com    end of file is reached, return (0, 0).
10713819Sgabeblack@google.com    """
10813819Sgabeblack@google.com    result = 0
10913819Sgabeblack@google.com    shift = 0
11013819Sgabeblack@google.com    pos = 0
11113819Sgabeblack@google.com    # Use a 32-bit mask
11213819Sgabeblack@google.com    mask = 0xffffffff
11313819Sgabeblack@google.com    while 1:
11413819Sgabeblack@google.com        c = in_file.read(1)
11513819Sgabeblack@google.com        if len(c) == 0:
11613819Sgabeblack@google.com            return (0, 0)
11713819Sgabeblack@google.com        b = struct.unpack('<B', c)[0]
11813819Sgabeblack@google.com        result |= ((b & 0x7f) << shift)
11913819Sgabeblack@google.com        pos += 1
12013819Sgabeblack@google.com        if not (b & 0x80):
12113819Sgabeblack@google.com            if result > 0x7fffffffffffffff:
12213819Sgabeblack@google.com                result -= (1 << 64)
12313819Sgabeblack@google.com                result |= ~mask
12413819Sgabeblack@google.com            else:
125                result &= mask
126            return (result, pos)
127        shift += 7
128        if shift >= 64:
129            raise IOError('Too many bytes when decoding varint.')
130
131def decodeMessage(in_file, message):
132    """
133    Attempt to read a message from the file and decode it. Return
134    False if no message could be read.
135    """
136    try:
137        size, pos = _DecodeVarint32(in_file)
138        if size == 0:
139            return False
140        buf = in_file.read(size)
141        message.ParseFromString(buf)
142        return True
143    except IOError:
144        return False
145
146def _EncodeVarint32(out_file, value):
147  """
148  The encoding of the Varint32 is copied from
149  google.protobuf.internal.encoder and is only repeated here to
150  avoid depending on the internal functions in the library.
151  """
152  bits = value & 0x7f
153  value >>= 7
154  while value:
155    out_file.write(struct.pack('<B', 0x80 | bits))
156    bits = value & 0x7f
157    value >>= 7
158  out_file.write(struct.pack('<B', bits))
159
160def encodeMessage(out_file, message):
161    """
162    Encoded a message with the length prepended as a 32-bit varint.
163    """
164    out = message.SerializeToString()
165    _EncodeVarint32(out_file, len(out))
166    out_file.write(out)
167