protolib.py revision 10269
112837Sgabeblack@google.com#!/usr/bin/env python
212837Sgabeblack@google.com
312837Sgabeblack@google.com# Copyright (c) 2013 ARM Limited
412837Sgabeblack@google.com# All rights reserved
512837Sgabeblack@google.com#
612837Sgabeblack@google.com# The license below extends only to copyright in the software and shall
712837Sgabeblack@google.com# not be construed as granting a license to any other intellectual
812837Sgabeblack@google.com# property including but not limited to intellectual property relating
912837Sgabeblack@google.com# to a hardware implementation of the functionality of the software
1012837Sgabeblack@google.com# licensed hereunder.  You may use the software subject to the license
1112837Sgabeblack@google.com# terms below provided that you ensure that this notice is replicated
1212837Sgabeblack@google.com# unmodified and in its entirety in all distributions of the software,
1312837Sgabeblack@google.com# modified or unmodified, in source code or in binary form.
1412837Sgabeblack@google.com#
1512837Sgabeblack@google.com# Redistribution and use in source and binary forms, with or without
1612837Sgabeblack@google.com# modification, are permitted provided that the following conditions are
1712837Sgabeblack@google.com# met: redistributions of source code must retain the above copyright
1812837Sgabeblack@google.com# notice, this list of conditions and the following disclaimer;
1912837Sgabeblack@google.com# redistributions in binary form must reproduce the above copyright
2012837Sgabeblack@google.com# notice, this list of conditions and the following disclaimer in the
2112837Sgabeblack@google.com# documentation and/or other materials provided with the distribution;
2212837Sgabeblack@google.com# neither the name of the copyright holders nor the names of its
2312837Sgabeblack@google.com# contributors may be used to endorse or promote products derived from
2412837Sgabeblack@google.com# this software without specific prior written permission.
2512837Sgabeblack@google.com#
2612837Sgabeblack@google.com# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
2712837Sgabeblack@google.com# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
2812837Sgabeblack@google.com# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
2912837Sgabeblack@google.com# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
3012948Sgabeblack@google.com# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
3112948Sgabeblack@google.com# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3212837Sgabeblack@google.com# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
3312837Sgabeblack@google.com# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
3412837Sgabeblack@google.com# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
3512837Sgabeblack@google.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3612837Sgabeblack@google.com# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3712837Sgabeblack@google.com#
3812948Sgabeblack@google.com# Copyright 2008 Google Inc.  All rights reserved.
3912948Sgabeblack@google.com# http://code.google.com/p/protobuf/
4012948Sgabeblack@google.com#
4112837Sgabeblack@google.com# Redistribution and use in source and binary forms, with or without
4212948Sgabeblack@google.com# modification, are permitted provided that the following conditions are
4312837Sgabeblack@google.com# met:
4412837Sgabeblack@google.com#
4512837Sgabeblack@google.com#     * Redistributions of source code must retain the above copyright
4612837Sgabeblack@google.com# notice, this list of conditions and the following disclaimer.
4712948Sgabeblack@google.com#     * Redistributions in binary form must reproduce the above
4812837Sgabeblack@google.com# copyright notice, this list of conditions and the following disclaimer
4912837Sgabeblack@google.com# in the documentation and/or other materials provided with the
5012837Sgabeblack@google.com# distribution.
5112837Sgabeblack@google.com#     * Neither the name of Google Inc. nor the names of its
5212837Sgabeblack@google.com# contributors may be used to endorse or promote products derived from
5312948Sgabeblack@google.com# this software without specific prior written permission.
5412837Sgabeblack@google.com#
5512837Sgabeblack@google.com# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
5612837Sgabeblack@google.com# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5712837Sgabeblack@google.com# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
5812837Sgabeblack@google.com# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
5912948Sgabeblack@google.com# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
6012837Sgabeblack@google.com# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
6112837Sgabeblack@google.com# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
6212837Sgabeblack@google.com# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
6312837Sgabeblack@google.com# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
6412837Sgabeblack@google.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
6512948Sgabeblack@google.com# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
6612837Sgabeblack@google.com#
6712837Sgabeblack@google.com# Authors: Andreas Hansson
6812948Sgabeblack@google.com#          Radhika Jagtap
6912948Sgabeblack@google.com
7012948Sgabeblack@google.com# This file is a library of commonly used functions used when interfacing
7112898Sgabeblack@google.com# with protobuf python messages. For eg, the decode scripts for different
7212898Sgabeblack@google.com# types of proto objects can use the same function to decode a single message
7312948Sgabeblack@google.com
7412898Sgabeblack@google.comimport gzip
7512948Sgabeblack@google.comimport struct
7612948Sgabeblack@google.com
7712948Sgabeblack@google.comdef openFileRd(in_file):
7812948Sgabeblack@google.com    """
7912948Sgabeblack@google.com    This opens the file passed as argument for reading using an appropriate
8012898Sgabeblack@google.com    function depending on if it is gzipped or not. It returns the file
8112898Sgabeblack@google.com    handle.
8212898Sgabeblack@google.com    """
8312898Sgabeblack@google.com    try:
8412898Sgabeblack@google.com        # First see if this file is gzipped
8512948Sgabeblack@google.com        try:
8612948Sgabeblack@google.com            # Opening the file works even if it is not a gzip file
8712948Sgabeblack@google.com            proto_in = gzip.open(in_file, 'rb')
8812898Sgabeblack@google.com
8912898Sgabeblack@google.com            # Force a check of the magic number by seeking in the
9012898Sgabeblack@google.com            # file. If we do not do it here the error will occur when
9112898Sgabeblack@google.com            # reading the first message.
9212898Sgabeblack@google.com            proto_in.seek(1)
9312898Sgabeblack@google.com            proto_in.seek(0)
9412948Sgabeblack@google.com        except IOError:
9512948Sgabeblack@google.com            proto_in = open(in_file, 'rb')
9612948Sgabeblack@google.com    except IOError:
9712898Sgabeblack@google.com        print "Failed to open ", in_file, " for reading"
9812898Sgabeblack@google.com        exit(-1)
9912898Sgabeblack@google.com    return proto_in
10012898Sgabeblack@google.com
10112898Sgabeblack@google.comdef DecodeVarint(in_file):
10212898Sgabeblack@google.com    """
10312948Sgabeblack@google.com    The decoding of the Varint32 is copied from
10412948Sgabeblack@google.com    google.protobuf.internal.decoder and is only repeated here to
10512948Sgabeblack@google.com    avoid depending on the internal functions in the library. If the
10612948Sgabeblack@google.com    end of file is reached, return (0, 0).
10712948Sgabeblack@google.com    """
10812948Sgabeblack@google.com    result = 0
10912948Sgabeblack@google.com    shift = 0
11012948Sgabeblack@google.com    pos = 0
11112898Sgabeblack@google.com    # Use a 32-bit mask
11212898Sgabeblack@google.com    mask = 0xffffffff
11312898Sgabeblack@google.com    while 1:
11412948Sgabeblack@google.com        c = in_file.read(1)
11512948Sgabeblack@google.com        if len(c) == 0:
11612948Sgabeblack@google.com            return (0, 0)
11712898Sgabeblack@google.com        b = struct.unpack('<B', c)[0]
11812837Sgabeblack@google.com        result |= ((b & 0x7f) << shift)
119        pos += 1
120        if not (b & 0x80):
121            if result > 0x7fffffffffffffff:
122                result -= (1 << 64)
123                result |= ~mask
124            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 = DecodeVarint(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 EncodeVarint(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    EncodeVarint(out_file, len(out))
166    out_file.write(out)
167