~widelands-dev/widelands-website/trunk

« back to all changes in this revision

Viewing changes to wlms/utils.py

  • Committer: Holger Rapp
  • Date: 2010-01-01 20:08:18 UTC
  • mto: (173.3.2 widelands)
  • mto: This revision was merged to the branch mainline in revision 176.
  • Revision ID: rapp@mrt.uka.de-20100101200818-znihhmyhlx0o33gp
Added diff_match_patch from google, because they do not provide a setup.py

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/env python
2
 
# encoding: utf-8
3
 
 
4
 
__all__ = ["make_packet", "Packet"]
5
 
 
6
 
from wlms.errors import MSGarbageError
7
 
 
8
 
class Packet(object):
9
 
    def __init__(self, args):
10
 
        """Convenience wrapper around a received packet"""
11
 
        self._args = args
12
 
 
13
 
    def string(self):
14
 
        try:
15
 
            return self._args.pop(0)
16
 
        except IndexError:
17
 
            raise MSGarbageError("Wanted a string but got no arguments left")
18
 
 
19
 
    def int(self):
20
 
        s = self.string()
21
 
        try:
22
 
            return int(s)
23
 
        except ValueError:
24
 
            raise MSGarbageError("Invalid integer: %r" % s)
25
 
 
26
 
    def bool(self):
27
 
        s = self.string()
28
 
        if s == "1" or s.lower() == "true":
29
 
            return True
30
 
        elif s == "0" or s.lower() == "false":
31
 
            return False
32
 
        raise MSGarbageError("Invalid bool: %r" % s)
33
 
 
34
 
    def unpack(self, codes):
35
 
        return [ self._CODES2FUNC[c](self) for c in codes ]
36
 
 
37
 
    _CODES2FUNC = {
38
 
        "i": int,
39
 
        "s": string,
40
 
        "b": bool,
41
 
    }
42
 
 
43
 
 
44
 
def make_packet(*args):
45
 
    pstr = ''.join(str(x) + '\x00' for x in args)
46
 
    size = len(pstr) + 2
47
 
    return chr(size >> 8) + chr(size & 0xff) + pstr
48
 
 
49
 
 
50