2 # Copyright (c) 2018 Cisco and/or its affiliates.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
18 from enum import IntEnum
22 # Set log-level in application by doing e.g.:
23 # logger = logging.getLogger('vpp_serializer')
24 # logger.setLevel(logging.DEBUG)
26 logger = logging.getLogger(__name__)
30 def __init__(self, type, elements=0):
31 base_types = {'u8': '>B',
39 if elements > 0 and type == 'u8':
40 self.packer = struct.Struct('>%ss' % elements)
42 self.packer = struct.Struct(base_types[type])
43 self.size = self.packer.size
44 logger.debug('Adding {} with format: {}'
45 .format(type, base_types[type]))
47 def pack(self, data, kwargs=None):
48 return self.packer.pack(data)
50 def unpack(self, data, offset, result=None):
51 return self.packer.unpack_from(data, offset)[0]
55 types['u8'] = BaseTypes('u8')
56 types['u16'] = BaseTypes('u16')
57 types['u32'] = BaseTypes('u32')
58 types['i32'] = BaseTypes('i32')
59 types['u64'] = BaseTypes('u64')
60 types['f64'] = BaseTypes('f64')
64 def __init__(self, name, field_type, num):
67 self.packer = BaseTypes(field_type, num)
68 self.size = self.packer.size
70 def pack(self, list, kwargs):
71 """Packs a fixed length bytestring. Left-pads with zeros
72 if input data is too short."""
73 if len(list) > self.num:
74 raise ValueError('Fixed list length error for "{}", got: {}'
76 .format(self.name, len(list), self.num))
77 return self.packer.pack(list)
79 def unpack(self, data, offset=0, result=None):
80 if len(data[offset:]) < self.num:
81 raise ValueError('Invalid array length for "{}" got {}'
83 .format(self.name, len(data), self.num))
84 return self.packer.unpack(data, offset)
88 def __init__(self, name, field_type, num):
90 self.packer = types[field_type]
91 self.size = self.packer.size * num
93 def pack(self, list, kwargs):
94 if len(list) != self.num:
95 raise ValueError('Fixed list length error, got: {} expected: {}'
96 .format(len(list), self.num))
99 b += self.packer.pack(e)
102 def unpack(self, data, offset=0, result=None):
103 # Return a list of arguments
105 for e in range(self.num):
106 x = self.packer.unpack(data, offset)
108 offset += self.packer.size
113 def __init__(self, name, field_type, len_field_name, index):
115 self.packer = types[field_type]
116 self.size = self.packer.size
117 self.length_field = len_field_name
119 def pack(self, list, kwargs=None):
120 if len(list) != kwargs[self.length_field]:
121 raise ValueError('Variable length error, got: {} expected: {}'
122 .format(len(list), kwargs[self.length_field]))
126 if self.packer.size == 1:
127 return bytearray(list)
130 b += self.packer.pack(e)
133 def unpack(self, data, offset=0, result=None):
134 # Return a list of arguments
137 if self.packer.size == 1:
138 if result[self.index] == 0:
140 p = BaseTypes('u8', result[self.index])
141 r = p.unpack(data, offset)
145 for e in range(result[self.index]):
146 x = self.packer.unpack(data, offset)
148 offset += self.packer.size
152 class VLAList_legacy():
153 def __init__(self, name, field_type):
154 self.packer = types[field_type]
155 self.size = self.packer.size
157 def pack(self, list, kwargs=None):
158 if self.packer.size == 1:
163 b += self.packer.pack(e)
166 def unpack(self, data, offset=0, result=None):
167 # Return a list of arguments
168 if (len(data) - offset) % self.packer.size:
169 raise ValueError('Legacy Variable Length Array length mismatch.')
170 elements = int((len(data) - offset) / self.packer.size)
172 for e in range(elements):
173 x = self.packer.unpack(data, offset)
175 offset += self.packer.size
180 def __init__(self, name, msgdef):
181 self.size = types['u32'].size
184 if type(f) is dict and 'enumtype' in f:
185 if f['enumtype'] != 'u32':
186 raise NotImplementedError
189 e_hash[ename] = evalue
190 self.enum = IntEnum(name, e_hash)
192 logger.debug('Adding enum {}'.format(name))
194 def __getattr__(self, name):
195 return self.enum[name]
197 def pack(self, data, kwargs=None):
198 return types['u32'].pack(data, kwargs)
200 def unpack(self, data, offset=0, result=None):
201 x = types['u32'].unpack(data, offset)
205 class VPPUnionType():
206 def __init__(self, name, msgdef):
211 self.packers = collections.OrderedDict()
212 for i, f in enumerate(msgdef):
213 if type(f) is dict and 'crc' in f:
217 if f_type not in types:
218 logger.debug('Unknown union type {}'.format(f_type))
219 raise ValueError('Unknown message type {}'.format(f_type))
220 fields.append(f_name)
221 size = types[f_type].size
222 self.packers[f_name] = types[f_type]
228 self.tuple = collections.namedtuple(name, fields, rename=True)
229 logger.debug('Adding union {}'.format(name))
231 def pack(self, data, kwargs=None):
232 for k, v in data.items():
233 logger.debug("Key: {} Value: {}".format(k, v))
234 b = self.packers[k].pack(v, kwargs)
236 r = bytearray(self.size)
240 def unpack(self, data, offset=0, result=None):
242 for k, p in self.packers.items():
243 r.append(p.unpack(data, offset))
244 return self.tuple._make(r)
248 # Set everything up to be able to pack / unpack
249 def __init__(self, name, msgdef):
255 self.field_by_name = {}
257 for i, f in enumerate(msgdef):
258 if type(f) is dict and 'crc' in f:
261 f_type, f_name = f[:2]
262 self.fields.append(f_name)
263 self.field_by_name[f_name] = None
264 self.fieldtypes.append(f_type)
265 if f_type not in types:
266 logger.debug('Unknown type {}'.format(f_type))
267 raise ValueError('Unknown message type {}'.format(f_type))
268 if len(f) == 3: # list
270 if list_elements == 0:
271 p = VLAList_legacy(f_name, f_type)
272 self.packers.append(p)
274 p = FixedList_u8(f_name, f_type, list_elements)
275 self.packers.append(p)
278 p = FixedList(f_name, f_type, list_elements)
279 self.packers.append(p)
281 elif len(f) == 4: # Variable length list
282 # Find index of length field
283 length_index = self.fields.index(f[3])
284 p = VLAList(f_name, f_type, f[3], length_index)
285 self.packers.append(p)
287 self.packers.append(types[f_type])
288 size += types[f_type].size
291 self.tuple = collections.namedtuple(name, self.fields, rename=True)
293 logger.debug('Adding type {}'.format(name))
295 def pack(self, data, kwargs=None):
299 for i, a in enumerate(self.fields):
301 b += b'\x00' * self.packers[i].size
304 if isinstance(self.packers[i], VPPType):
305 b += self.packers[i].pack(data[a], kwargs[a])
307 b += self.packers[i].pack(data[a], kwargs)
310 def unpack(self, data, offset=0, result=None):
311 # Return a list of arguments
313 for p in self.packers:
314 x = p.unpack(data, offset, result)
315 if type(x) is tuple and len(x) == 1:
319 return self.tuple._make(result)
322 class VPPMessage(VPPType):