~widelands-dev/widelands-website/trunk

« back to all changes in this revision

Viewing changes to wlms/utils.py

  • Committer: Holger Rapp
  • Date: 2012-03-17 16:22:06 UTC
  • Revision ID: sirver@gmx.de-20120317162206-fgttamk22qt1nytj
Let post count be calculated automatically instead of keeping track of it manually. Let's see how this affects performance

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