Package dns :: Module wiredata
[hide private]
[frames] | no frames]

Source Code for Module dns.wiredata

 1  # Copyright (C) 2011 Nominum, Inc. 
 2  # 
 3  # Permission to use, copy, modify, and distribute this software and its 
 4  # documentation for any purpose with or without fee is hereby granted, 
 5  # provided that the above copyright notice and this permission notice 
 6  # appear in all copies. 
 7  # 
 8  # THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES 
 9  # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 
10  # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR 
11  # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 
12  # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 
13  # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT 
14  # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 
15   
16  """DNS Wire Data Helper""" 
17   
18   
19  import dns.exception 
20  from ._compat import binary_type, string_types 
21   
22  # Figure out what constant python passes for an unspecified slice bound. 
23  # It's supposed to be sys.maxint, yet on 64-bit windows sys.maxint is 2^31 - 1 
24  # but Python uses 2^63 - 1 as the constant.  Rather than making pointless 
25  # extra comparisons, duplicating code, or weakening WireData, we just figure 
26  # out what constant Python will use. 
27   
28   
29 -class _SliceUnspecifiedBound(str):
30
31 - def __getslice__(self, i, j):
32 return j
33 34 _unspecified_bound = _SliceUnspecifiedBound('')[1:] 35 36
37 -class WireData(binary_type):
38 # WireData is a string with stricter slicing 39
40 - def __getitem__(self, key):
41 try: 42 if isinstance(key, slice): 43 return WireData(super(WireData, self).__getitem__(key)) 44 return bytearray(self.unwrap())[key] 45 except IndexError: 46 raise dns.exception.FormError
47
48 - def __getslice__(self, i, j):
49 try: 50 if j == _unspecified_bound: 51 # handle the case where the right bound is unspecified 52 j = len(self) 53 if i < 0 or j < 0: 54 raise dns.exception.FormError 55 # If it's not an empty slice, access left and right bounds 56 # to make sure they're valid 57 if i != j: 58 super(WireData, self).__getitem__(i) 59 super(WireData, self).__getitem__(j - 1) 60 return WireData(super(WireData, self).__getslice__(i, j)) 61 except IndexError: 62 raise dns.exception.FormError
63
64 - def __iter__(self):
65 i = 0 66 while 1: 67 try: 68 yield self[i] 69 i += 1 70 except dns.exception.FormError: 71 raise StopIteration
72
73 - def unwrap(self):
74 return binary_type(self)
75 76
77 -def maybe_wrap(wire):
78 if isinstance(wire, WireData): 79 return wire 80 elif isinstance(wire, binary_type): 81 return WireData(wire) 82 elif isinstance(wire, string_types): 83 return WireData(wire.encode()) 84 raise ValueError("unhandled type %s" % type(wire))
85