papi: add support for enumflag part 1 of 2
[vpp.git] / src / vpp-api / python / vpp_papi / vpp_serializer.py
index 649b5b1..644aeac 100644 (file)
 # limitations under the License.
 #
 import collections
+from enum import IntFlag
 import logging
 import socket
 import struct
 import sys
 
-if sys.version_info <= (3, 4):
-    from aenum import IntEnum  # noqa: F401
-else:
-    from enum import IntEnum  # noqa: F401
+from . import vpp_format
 
-if sys.version_info <= (3, 6):
-    from aenum import IntFlag  # noqa: F401
-else:
-
-    from enum import IntFlag  # noqa: F401
-
-from . import vpp_format  # noqa: E402
 
 #
 # Set log-level in application by doing e.g.:
 # logger = logging.getLogger('vpp_serializer')
 # logger.setLevel(logging.DEBUG)
 #
-logger = logging.getLogger(__name__)
+logger = logging.getLogger('vpp_papi.serializer')
+
 
-if sys.version[0] == '2':
-    def check(d): type(d) is dict
-else:
-    def check(d): type(d) is dict or type(d) is bytes
+def check(d):
+    return type(d) is dict or type(d) is bytes
 
 
 def conversion_required(data, field_type):
@@ -66,8 +56,7 @@ def conversion_unpacker(data, field_type):
     return vpp_format.conversion_unpacker_table[field_type](data)
 
 
-# TODO: post 20.01, remove inherit from object.
-class Packer(object):
+class Packer:
     options = {}
 
     def pack(self, data, kwargs):
@@ -77,18 +66,20 @@ class Packer(object):
         raise NotImplementedError
 
     # override as appropriate in subclasses
-    def _get_packer_with_options(self, f_type, options):
+    @staticmethod
+    def _get_packer_with_options(f_type, options):
         return types[f_type]
 
     def get_packer_with_options(self, f_type, options):
         if options is not None:
             try:
-                return self._get_packer_with_options(f_type, options)
+                c = types[f_type].__class__
+                return c._get_packer_with_options(f_type, options)
             except IndexError:
                 raise VPPSerializerValueError(
                     "Options not supported for {}{} ({})".
-                        format(f_type, types[f_type].__class__,
-                               options))
+                    format(f_type, types[f_type].__class__,
+                           options))
 
 
 class BaseTypes(Packer):
@@ -126,9 +117,9 @@ class BaseTypes(Packer):
     def unpack(self, data, offset, result=None, ntc=False):
         return self.packer.unpack_from(data, offset)[0], self.packer.size
 
-    def _get_packer_with_options(self, f_type, options):
-        c = types[f_type].__class__
-        return c(f_type, options=options)
+    @staticmethod
+    def _get_packer_with_options(f_type, options):
+        return BaseTypes(f_type, options=options)
 
     def __repr__(self):
         return "BaseTypes(type=%s, elements=%s, options=%s)" % (self._type,
@@ -146,8 +137,8 @@ class String(Packer):
         self.fixed = True if num else False
         if self.fixed and not self.limit:
             raise VPPSerializerValueError(
-                "Invalid argument length for: {}, {} maximum {}".
-                format(list, len(list), self.limit))
+                "Invalid combination for: {}, {} fixed:{} limit:{}".
+                format(name, options, self.fixed, self.limit))
 
     def pack(self, list, kwargs=None):
         if not list:
@@ -175,7 +166,6 @@ class String(Packer):
             return '', 0
         p = BaseTypes('u8', length)
         x, size = p.unpack(data, offset + length_field_size)
-        #x2 = x.split(b'\0', 1)[0]
         return (x.decode('ascii', errors='replace'), size + length_field_size)
 
 
@@ -271,8 +261,8 @@ class FixedList(Packer):
         return result, total
 
     def __repr__(self):
-        return "FixedList_(name=%s, field_type=%s, num=%s)" % (
-            self.name, self.field_type, self.num )
+        return "FixedList(name=%s, field_type=%s, num=%s)" % (
+            self.name, self.field_type, self.num)
 
 
 class VLAList(Packer):
@@ -325,8 +315,8 @@ class VLAList(Packer):
     def __repr__(self):
         return "VLAList(name=%s, field_type=%s, " \
                "len_field_name=%s, index=%s)" % (
-            self.name, self.field_type, self.length_field, self.index
-        )
+                   self.name, self.field_type, self.length_field, self.index
+               )
 
 
 class VLAList_legacy(Packer):
@@ -366,7 +356,10 @@ class VLAList_legacy(Packer):
         )
 
 
+# Will change to IntEnum after 21.04 release
 class VPPEnumType(Packer):
+    output_class = IntFlag
+
     def __init__(self, name, msgdef, options=None):
         self.size = types['u32'].size
         self.name = name
@@ -381,9 +374,9 @@ class VPPEnumType(Packer):
                 continue
             ename, evalue = f
             e_hash[ename] = evalue
-        self.enum = IntFlag(name, e_hash)
+        self.enum = self.output_class(name, e_hash)
         types[name] = self
-        class_types[name] = VPPEnumType
+        class_types[name] = self.__class__
         self.options = options
 
     def __getattr__(self, name):
@@ -392,10 +385,6 @@ class VPPEnumType(Packer):
     def __bool__(self):
         return True
 
-    # TODO: Remove post 20.01.
-    if sys.version[0] == '2':
-        __nonzero__ = __bool__
-
     def pack(self, data, kwargs=None):
         if data is None:  # Default to zero if not specified
             if self.options and 'default' in self.options:
@@ -409,16 +398,23 @@ class VPPEnumType(Packer):
         x, size = types[self.enumtype].unpack(data, offset)
         return self.enum(x), size
 
-    def _get_packer_with_options(self, f_type, options):
-        c = types[f_type].__class__
-        return c(f_type, types[f_type].msgdef, options=options)
+    @classmethod
+    def _get_packer_with_options(cls, f_type, options):
+        return cls(f_type, types[f_type].msgdef, options=options)
 
     def __repr__(self):
-        return "VPPEnumType(name=%s, msgdef=%s, options=%s)" % (
-            self.name, self.msgdef, self.options
+        return "%s(name=%s, msgdef=%s, options=%s)" % (
+            self.__class__.__name__, self.name, self.msgdef, self.options
         )
 
 
+class VPPEnumFlagType(VPPEnumType):
+    output_class = IntFlag
+
+    def __init__(self, name, msgdef, options=None):
+        super(VPPEnumFlagType, self).__init__(name, msgdef, options)
+
+
 class VPPUnionType(Packer):
     def __init__(self, name, msgdef):
         self.name = name
@@ -512,9 +508,9 @@ class VPPTypeAlias(Packer):
 
         return self.packer.pack(data, kwargs)
 
-    def _get_packer_with_options(self, f_type, options):
-        c = types[f_type].__class__
-        return c(f_type, types[f_type].msgdef, options=options)
+    @staticmethod
+    def _get_packer_with_options(f_type, options):
+        return VPPTypeAlias(f_type, types[f_type].msgdef, options=options)
 
     def unpack(self, data, offset=0, result=None, ntc=False):
         if ntc is False and self.name in vpp_format.conversion_unpacker_table: