1 # Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
2 # Copyright (C) 2015 YAMAMOTO Takashi <yamamoto at valinux co jp>
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
8 # http://www.apache.org/licenses/LICENSE-2.0
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
21 from ryu.lib import addrconv
24 class TypeDescr(object):
28 class IntDescr(TypeDescr):
29 def __init__(self, size):
32 def to_user(self, binary):
34 for _ in range(self.size):
40 def from_user(self, i):
42 for _ in range(self.size):
43 binary = six.int2byte(i & 255) + binary
59 split string into list of strings by specified number.
62 return [s[i:i + n] for i in range(0, length, n)]
65 class IntDescrMlt(TypeDescr):
66 def __init__(self, length, num):
69 self.size = length * num
71 def to_user(self, binary):
72 assert len(binary) == self.size
73 lb = _split_str(binary, self.length)
77 for _ in range(self.length):
84 def from_user(self, li):
85 assert len(li) == self.num
89 for _ in range(self.length):
90 b = six.int2byte(i & 255) + b
96 Int4Double = IntDescrMlt(4, 2)
99 class MacAddr(TypeDescr):
101 to_user = addrconv.mac.bin_to_text
102 from_user = addrconv.mac.text_to_bin
105 class IPv4Addr(TypeDescr):
107 to_user = addrconv.ipv4.bin_to_text
108 from_user = addrconv.ipv4.text_to_bin
111 class IPv6Addr(TypeDescr):
113 to_user = addrconv.ipv6.bin_to_text
114 from_user = addrconv.ipv6.text_to_bin
117 class UnknownType(TypeDescr):
122 return base64.b64encode(data).decode('ascii')
124 return base64.b64encode(data)
126 from_user = staticmethod(base64.b64decode)
129 class TypeDisp(object):
135 def register_unknown_type(cls):
136 def _register_type(subcls):
137 cls._UNKNOWN_TYPE = subcls
139 return _register_type
142 def register_type(cls, type_):
143 cls._TYPES = cls._TYPES.copy()
145 def _register_type(subcls):
146 cls._TYPES[type_] = subcls
147 cls._REV_TYPES = None
149 return _register_type
152 def _lookup_type(cls, type_):
154 return cls._TYPES[type_]
156 return cls._UNKNOWN_TYPE
159 def _rev_lookup_type(cls, targ_cls):
160 if cls._REV_TYPES is None:
161 rev = dict((v, k) for k, v in cls._TYPES.items())
163 return cls._REV_TYPES[targ_cls]