~martin-decky/helenos/rcu

« back to all changes in this revision

Viewing changes to tools/xstruct.py

  • Committer: Vojtech Horky
  • Date: 2012-05-22 10:31:25 UTC
  • mto: (1460.2.42 mainline)
  • mto: This revision was merged to the branch mainline in revision 1479.
  • Revision ID: vojtechhorky@users.sourceforge.net-20120522103125-xy2p37couqxwhz09
Make tools work with Python 3 again

Show diffs side-by-side

added added

removed removed

Lines of Context:
34
34
import sys
35
35
import types
36
36
 
 
37
# Handle long integer conversions nicely in both Python 2 and Python 3
37
38
integer_types = (int, long) if sys.version < '3' else (int,)
38
39
 
 
40
# Ensure that 's' format for struct receives correct data type depending
 
41
# on Python version (needed due to different way to encode into bytes) 
 
42
ensure_string = \
 
43
        (lambda value: value if type(value) is str else bytes(value)) \
 
44
                if sys.version < '3' else \
 
45
        (lambda value: bytes(value, 'ascii') if type(value) is str else value)
 
46
 
39
47
ranges = {
40
48
        'B': (integer_types, 0x00, 0xff),
41
49
        'H': (integer_types, 0x0000, 0xffff),
76
84
                                        check_range(variable + '[' + repr(index) + ']', fmt, item)
77
85
                                        args.append(item)
78
86
                        else:
 
87
                                if (fmt == "s"):
 
88
                                        value = ensure_string(value)
79
89
                                check_range(variable, fmt, value)
80
90
                                args.append(value)              
81
91
                return struct.pack(self._format_, *args)