blob: 7cfe514a2046489c19d658edca79c9bcdbe72713 [file] [log] [blame]
Alexander Afanasyev5ba90362013-07-15 19:58:38 -07001## -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
2#
3# Copyright (c) 2011-2013, Regents of the University of California
4# Alexander Afanasyev
5#
6# GNU 3.0 license, See the LICENSE file for more information
7#
8# Author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
9#
10
11#
12# Based on PyCCN code, copyrighted and licensed as follows
13#
14# Copyright (c) 2011-2013, Regents of the University of California
15# BSD license, See the COPYING file for more information
16# Written by: Derek Kulinski <takeda@takeda.tk>
17# Jeff Burke <jburke@ucla.edu>
18#
19
20import struct
21
22class Flag(int):
23 __initialized = False
24 _flags = None
25 _prefix = None
26 __flags_values__ = None
27
28 @classmethod
29 def initialize(cls):
30 cls._flags = {}
31 cls.__flags_values__ = {}
32 cls.__initialized = True
33
34 @classmethod
35 def new_flag(cls, name, value):
36 if not cls.__initialized:
37 cls.initialize()
38
39 cls._flags[value] = name
40
41 obj = cls(value)
42 cls.__flags_values__[value] = obj
43
44 return obj
45
46 def __new__(cls, value):
47 if cls.__flags_values__.has_key(value):
48 return cls.__flags_values__[value]
49
50 return super(Flag, cls).__new__(cls, value)
51
52 def generate_repr(self):
53 val = long(self)
54 flags = [name for i, name in self._flags.items() if i & val]
55 return " | ".join(flags)
56
57 def __repr__(self):
58 if self._prefix:
59 return self._prefix + "." + self.generate_repr()
60
61 t = type(self)
62 type_name = "%s.%s" % (t.__module__, t.__name__)
63 return "<flags %s of type %s>" % (self.generate_repr(), type_name)
64
65 def __and__(self, other):
66 cls = type(self)
67 return cls(long(self) & long(other))
68
69 def __xor__(self, other):
70 cls = type(self)
71 return cls(long(self) ^ long(other))
72
73 def __or__(self, other):
74 cls = type(self)
75 return cls(long(self) | long(other))
76
77class Enum(Flag):
78 def __new__(cls, value):
79 if cls.__flags_values__.has_key(value):
80 return cls.__flags_values__[value]
81
82 if cls._flags.has_key(value):
83 return super(Enum, cls).__new__(cls, value)
84
85 raise ValueError("invalid flag value: %d" % value)
86
87 def generate_repr(self):
88 return self._flags[long(self)]
89
90def ccn2py_time(value):
91 bintime = b'\x00' * (8 - len(value)) + value
92 inttime = struct.unpack("!Q", bintime)[0]
93 return inttime / 4096.0
94
95def py2ccn_time(value):
96 inttime = int(value * 4096 + 0.5)
97 bintime = struct.pack("!Q", inttime)
98 return bintime.lstrip(b'\x00')