1# encoding: utf-8 2""" 3asn.py 4 5Created by Thomas Mangin on 2010-01-15. 6Copyright (c) 2009-2017 Exa Networks. All rights reserved. 7License: 3-clause BSD. (See the COPYRIGHT file) 8""" 9 10from struct import pack 11from struct import unpack 12import sys 13 14from exabgp.protocol.resource import Resource 15 16if sys.version_info > (3,): 17 long = int 18 19# =================================================================== ASN 20 21 22class ASN(Resource): 23 MAX = pow(2, 16) - 1 24 25 def asn4(self): 26 return self > self.MAX 27 28 def pack(self, negotiated=None): 29 asn4 = negotiated if negotiated is not None else self.asn4() 30 return pack('!L' if asn4 else '!H', self) 31 32 @classmethod 33 def unpack(cls, data, klass=None): 34 kls = cls if klass is None else klass 35 value = unpack('!L' if len(data) == 4 else '!H', data)[0] 36 return kls(value) 37 38 def __len__(self): 39 return 4 if self.asn4() else 2 40 41 def extract(self): 42 return [pack('!L', self)] 43 44 def trans(self): 45 if self.asn4(): 46 return AS_TRANS 47 return self 48 49 def __repr__(self): 50 return '%ld' % long(self) 51 52 def __str__(self): 53 return '%ld' % long(self) 54 55 @classmethod 56 def from_string(cls, value): 57 return cls(long(value)) 58 59 60AS_TRANS = ASN(23456) 61