Rev 3971: Fix bencoding of bools, in file:///home/pqm/archives/thelove/bzr/%2Btrunk/

Canonical.com Patch Queue Manager pqm at pqm.ubuntu.com
Thu Jan 29 06:41:48 GMT 2009


At file:///home/pqm/archives/thelove/bzr/%2Btrunk/

------------------------------------------------------------
revno: 3971
revision-id: pqm at pqm.ubuntu.com-20090129064144-7kz4ibeppmn41zs9
parent: pqm at pqm.ubuntu.com-20090129060443-6hvfgxb55cd6r527
parent: andrew.bennetts at canonical.com-20090129013651-qbt3lnl9i7jm89a3
committer: Canonical.com Patch Queue Manager <pqm at pqm.ubuntu.com>
branch nick: +trunk
timestamp: Thu 2009-01-29 06:41:44 +0000
message:
  Fix bencoding of bools,
  	provide a bdecode_as_tuple function. (Andrew Bennetts)
modified:
  bzrlib/util/bencode.py         bencode.py-20070220044742-sltr28q21w2wzlxi-1
  bzrlib/util/tests/test_bencode.py test_bencode.py-20070713042202-qjw8rppxaz7ky6i6-1
    ------------------------------------------------------------
    revno: 3923.4.2
    revision-id: andrew.bennetts at canonical.com-20090129013651-qbt3lnl9i7jm89a3
    parent: andrew.bennetts at canonical.com-20090107021847-iugqd7lq1lrtcebd
    committer: Andrew Bennetts <andrew.bennetts at canonical.com>
    branch nick: bencode-tweak
    timestamp: Thu 2009-01-29 12:36:51 +1100
    message:
      Tweaks prompted by John's review.
    modified:
      bzrlib/util/bencode.py         bencode.py-20070220044742-sltr28q21w2wzlxi-1
      bzrlib/util/tests/test_bencode.py test_bencode.py-20070713042202-qjw8rppxaz7ky6i6-1
    ------------------------------------------------------------
    revno: 3923.4.1
    revision-id: andrew.bennetts at canonical.com-20090107021847-iugqd7lq1lrtcebd
    parent: pqm at pqm.ubuntu.com-20090106171520-9pzjoqa7m74hvhht
    committer: Andrew Bennetts <andrew.bennetts at canonical.com>
    branch nick: bencode-tweak
    timestamp: Wed 2009-01-07 13:18:47 +1100
    message:
      Fix encoding of bools, provide a bdecode_tuple function.
    modified:
      bzrlib/util/bencode.py         bencode.py-20070220044742-sltr28q21w2wzlxi-1
      bzrlib/util/tests/test_bencode.py test_bencode.py-20070713042202-qjw8rppxaz7ky6i6-1
=== modified file 'bzrlib/util/bencode.py'
--- a/bzrlib/util/bencode.py	2007-07-13 04:22:17 +0000
+++ b/bzrlib/util/bencode.py	2009-01-29 01:36:51 +0000
@@ -12,82 +12,94 @@
 # 
 # The above copyright notice and this permission notice shall be
 # included in all copies or substantial portions of the Software.
-# 
-# The Software is provided "AS IS", without warranty of any kind,
-# express or implied, including but not limited to the warranties of
-# merchantability,  fitness for a particular purpose and
-# noninfringement. In no event shall the  authors or copyright holders
-# be liable for any claim, damages or other liability, whether in an
-# action of contract, tort or otherwise, arising from, out of or in
-# connection with the Software or the use or other dealings in the
-# Software.
-
-def decode_int(x, f):
-    f += 1
-    newf = x.index('e', f)
-    try:
-        n = int(x[f:newf])
-    except (OverflowError, ValueError):
-        n = long(x[f:newf])
-    if x[f] == '-':
-        if x[f + 1] == '0':
-            raise ValueError
-    elif x[f] == '0' and newf != f+1:
-        raise ValueError
-    return (n, newf+1)
-
-def decode_string(x, f):
-    colon = x.index(':', f)
-    try:
-        n = int(x[f:colon])
-    except (OverflowError, ValueError):
-        n = long(x[f:colon])
-    if x[f] == '0' and colon != f+1:
-        raise ValueError
-    colon += 1
-    return (x[colon:colon+n], colon+n)
-
-def decode_list(x, f):
-    r, f = [], f+1
-    while x[f] != 'e':
-        v, f = decode_func[x[f]](x, f)
-        r.append(v)
-    return (r, f + 1)
-
-def decode_dict(x, f):
-    r, f = {}, f+1
-    lastkey = None
-    while x[f] != 'e':
-        k, f = decode_string(x, f)
-        if lastkey >= k:
-            raise ValueError
-        lastkey = k
-        r[k], f = decode_func[x[f]](x, f)
-    return (r, f + 1)
-
-decode_func = {}
-decode_func['l'] = decode_list
-decode_func['d'] = decode_dict
-decode_func['i'] = decode_int
-decode_func['0'] = decode_string
-decode_func['1'] = decode_string
-decode_func['2'] = decode_string
-decode_func['3'] = decode_string
-decode_func['4'] = decode_string
-decode_func['5'] = decode_string
-decode_func['6'] = decode_string
-decode_func['7'] = decode_string
-decode_func['8'] = decode_string
-decode_func['9'] = decode_string
-
-def bdecode(x):
-    try:
-        r, l = decode_func[x[0]](x, 0)
-    except (IndexError, KeyError):
-        raise ValueError
-    if l != len(x):
-        raise ValueError
-    return r
+#
+# Modifications copyright (C) 2008 Canonical Ltd
+
+class BDecoder(object):
+
+    def __init__(self, yield_tuples=False):
+        """Constructor.
+
+        :param yield_tuples: if true, decode "l" elements as tuples rather than
+            lists.
+        """
+        self.yield_tuples = yield_tuples
+        decode_func = {}
+        decode_func['l'] = self.decode_list
+        decode_func['d'] = self.decode_dict
+        decode_func['i'] = self.decode_int
+        decode_func['0'] = self.decode_string
+        decode_func['1'] = self.decode_string
+        decode_func['2'] = self.decode_string
+        decode_func['3'] = self.decode_string
+        decode_func['4'] = self.decode_string
+        decode_func['5'] = self.decode_string
+        decode_func['6'] = self.decode_string
+        decode_func['7'] = self.decode_string
+        decode_func['8'] = self.decode_string
+        decode_func['9'] = self.decode_string
+        self.decode_func = decode_func
+
+    def decode_int(self, x, f):
+        f += 1
+        newf = x.index('e', f)
+        try:
+            n = int(x[f:newf])
+        except (OverflowError, ValueError):
+            n = long(x[f:newf])
+        if x[f] == '-':
+            if x[f + 1] == '0':
+                raise ValueError
+        elif x[f] == '0' and newf != f+1:
+            raise ValueError
+        return (n, newf+1)
+
+    def decode_string(self, x, f):
+        colon = x.index(':', f)
+        try:
+            n = int(x[f:colon])
+        except (OverflowError, ValueError):
+            n = long(x[f:colon])
+        if x[f] == '0' and colon != f+1:
+            raise ValueError
+        colon += 1
+        return (x[colon:colon+n], colon+n)
+
+    def decode_list(self, x, f):
+        r, f = [], f+1
+        while x[f] != 'e':
+            v, f = self.decode_func[x[f]](x, f)
+            r.append(v)
+        if self.yield_tuples:
+            r = tuple(r)
+        return (r, f + 1)
+
+    def decode_dict(self, x, f):
+        r, f = {}, f+1
+        lastkey = None
+        while x[f] != 'e':
+            k, f = self.decode_string(x, f)
+            if lastkey >= k:
+                raise ValueError
+            lastkey = k
+            r[k], f = self.decode_func[x[f]](x, f)
+        return (r, f + 1)
+
+    def bdecode(self, x):
+        try:
+            r, l = self.decode_func[x[0]](x, 0)
+        except (IndexError, KeyError):
+            raise ValueError
+        if l != len(x):
+            raise ValueError
+        return r
+
+
+_decoder = BDecoder()
+bdecode = _decoder.bdecode
+
+_tuple_decoder = BDecoder(True)
+bdecode_as_tuple = _tuple_decoder.bdecode
 
 
 from types import StringType, IntType, LongType, DictType, ListType, TupleType
@@ -133,9 +145,13 @@
 
 try:
     from types import BooleanType
-    encode_func[BooleanType] = encode_int
 except ImportError:
     pass
+else:
+    def encode_bool(x,r):
+        encode_int(int(x), r)
+    encode_func[BooleanType] = encode_bool
+
 
 def bencode(x):
     r = []

=== modified file 'bzrlib/util/tests/test_bencode.py'
--- a/bzrlib/util/tests/test_bencode.py	2007-07-13 06:20:10 +0000
+++ b/bzrlib/util/tests/test_bencode.py	2009-01-29 01:36:51 +0000
@@ -23,7 +23,7 @@
 # Software.
 
 
-from bzrlib.util.bencode import bencode, bdecode, Bencached
+from bzrlib.util.bencode import bencode, bdecode, bdecode_as_tuple, Bencached
 from bzrlib.tests import TestCase
 
 class TestBencode(TestCase):
@@ -189,6 +189,25 @@
         bdecode('d0:i3ee')
 
 
+    def test_bdecode_as_tuple(self):
+        assert bdecode_as_tuple('le') == ()
+        try:
+            bdecode_as_tuple('leanfdldjfh')
+            assert 0
+        except ValueError:
+            pass
+        assert bdecode_as_tuple('l0:0:0:e') == ('', '', '')
+        assert bdecode_as_tuple('li1ei2ei3ee') == (1, 2, 3)
+        assert bdecode_as_tuple('l3:asd2:xye') == ('asd', 'xy')
+        assert bdecode_as_tuple('ll5:Alice3:Bobeli2ei3eee') == (('Alice', 'Bob'),
+                (2, 3))
+        try:
+            bdecode_as_tuple('l-3:e')
+            assert 0
+        except ValueError:
+            pass
+
+
     def test_bencode(self):
         assert bencode(4) == 'i4e'
         assert bencode(0) == 'i0e'
@@ -204,9 +223,12 @@
         assert bencode({'age': 25, 'eyes': 'blue'}) == 'd3:agei25e4:eyes4:bluee'
         assert bencode({'spam.mp3': {'author': 'Alice', 'length': 100000}}) == 'd8:spam.mp3d6:author5:Alice6:lengthi100000eee'
         assert bencode(Bencached(bencode(3))) == 'i3e'
+        assert bencode(True) == 'i1e'
+        assert bencode(False) == 'i0e'
         try:
             bencode({1: 'foo'})
+            assert 0
         except TypeError:
-            return
-        assert 0
+            pass
+
 




More information about the bazaar-commits mailing list