1 # ASN.1 named integers 2 from pyasn1 import error 3 4 __all__ = [ 'NamedValues' ] 5 6 class NamedValues: 7 def __init__(self, *namedValues): 8 self.nameToValIdx = {}; self.valToNameIdx = {} 9 self.namedValues = () 10 automaticVal = 1 11 for namedValue in namedValues: 12 if isinstance(namedValue, tuple): 13 name, val = namedValue 14 else: 15 name = namedValue 16 val = automaticVal 17 if name in self.nameToValIdx: 18 raise error.PyAsn1Error('Duplicate name %s' % (name,)) 19 self.nameToValIdx[name] = val 20 if val in self.valToNameIdx: 21 raise error.PyAsn1Error('Duplicate value %s=%s' % (name, val)) 22 self.valToNameIdx[val] = name 23 self.namedValues = self.namedValues + ((name, val),) 24 automaticVal = automaticVal + 1 25 def __str__(self): return str(self.namedValues) 26 27 def getName(self, value): 28 if value in self.valToNameIdx: 29 return self.valToNameIdx[value] 30 31 def getValue(self, name): 32 if name in self.nameToValIdx: 33 return self.nameToValIdx[name] 34 35 def __getitem__(self, i): return self.namedValues[i] 36 def __len__(self): return len(self.namedValues) 37 38 def __add__(self, namedValues): 39 return self.__class__(*self.namedValues + namedValues) 40 def __radd__(self, namedValues): 41 return self.__class__(*namedValues + tuple(self)) 42 43 def clone(self, *namedValues): 44 return self.__class__(*tuple(self) + namedValues) 45 46 # XXX clone/subtype? 47