mitmproxy/netlib/odict.py

184 lines
4.7 KiB
Python
Raw Normal View History

2014-08-16 13:53:07 +00:00
from __future__ import (absolute_import, print_function, division)
import copy
2015-09-17 14:31:50 +00:00
import six
from .utils import Serializable, safe_subn
2012-06-18 21:42:32 +00:00
2016-02-08 03:16:58 +00:00
class ODict(Serializable):
2012-06-18 21:42:32 +00:00
"""
A dictionary-like object for managing ordered (key, value) data. Think
about it as a convenient interface to a list of (key, value) tuples.
2012-06-18 21:42:32 +00:00
"""
2012-06-18 21:42:32 +00:00
def __init__(self, lst=None):
self.lst = lst or []
def _kconv(self, s):
return s
def __eq__(self, other):
return self.lst == other.lst
2014-09-04 17:18:43 +00:00
def __ne__(self, other):
return not self.__eq__(other)
2012-12-05 03:03:39 +00:00
def __iter__(self):
return self.lst.__iter__()
2012-06-18 21:42:32 +00:00
def __getitem__(self, k):
"""
Returns a list of values matching key.
"""
ret = []
k = self._kconv(k)
for i in self.lst:
if self._kconv(i[0]) == k:
ret.append(i[1])
return ret
2013-02-27 20:28:48 +00:00
def keys(self):
return list(set([self._kconv(i[0]) for i in self.lst]))
2012-06-18 21:42:32 +00:00
def _filter_lst(self, k, lst):
k = self._kconv(k)
new = []
for i in lst:
if self._kconv(i[0]) != k:
new.append(i)
return new
def __len__(self):
"""
Total number of (key, value) pairs.
"""
return len(self.lst)
def __setitem__(self, k, valuelist):
"""
Sets the values for key k. If there are existing values for this
key, they are cleared.
"""
2015-09-17 14:31:50 +00:00
if isinstance(valuelist, six.text_type) or isinstance(valuelist, six.binary_type):
raise ValueError(
"Expected list of values instead of string. "
2015-09-17 14:31:50 +00:00
"Example: odict[b'Host'] = [b'www.example.com']"
)
kc = self._kconv(k)
new = []
for i in self.lst:
if self._kconv(i[0]) == kc:
if valuelist:
new.append([k, valuelist.pop(0)])
else:
new.append(i)
while valuelist:
new.append([k, valuelist.pop(0)])
2012-06-18 21:42:32 +00:00
self.lst = new
def __delitem__(self, k):
"""
Delete all items matching k.
"""
self.lst = self._filter_lst(k, self.lst)
def __contains__(self, k):
2015-08-05 19:32:53 +00:00
k = self._kconv(k)
2012-06-18 21:42:32 +00:00
for i in self.lst:
2015-08-05 19:32:53 +00:00
if self._kconv(i[0]) == k:
2012-06-18 21:42:32 +00:00
return True
return False
2015-07-30 11:52:13 +00:00
def add(self, key, value, prepend=False):
if prepend:
self.lst.insert(0, [key, value])
else:
self.lst.append([key, value])
2012-06-18 21:42:32 +00:00
def get(self, k, d=None):
if k in self:
return self[k]
else:
return d
def get_first(self, k, d=None):
if k in self:
return self[k][0]
else:
return d
2012-06-18 21:42:32 +00:00
def items(self):
return self.lst[:]
def copy(self):
"""
Returns a copy of this object.
"""
lst = copy.deepcopy(self.lst)
return self.__class__(lst)
2015-04-14 01:50:57 +00:00
def extend(self, other):
"""
Add the contents of other, preserving any duplicates.
"""
self.lst.extend(other.lst)
2012-06-18 21:42:32 +00:00
def __repr__(self):
return repr(self.lst)
2012-06-18 21:42:32 +00:00
def in_any(self, key, value, caseless=False):
"""
Do any of the values matching key contain value?
If caseless is true, value comparison is case-insensitive.
"""
if caseless:
value = value.lower()
for i in self[key]:
if caseless:
i = i.lower()
if value in i:
return True
return False
def replace(self, pattern, repl, *args, **kwargs):
"""
Replaces a regular expression pattern with repl in both keys and
values. Encoded content will be decoded before replacement, and
re-encoded afterwards.
Returns the number of replacements made.
"""
nlst, count = [], 0
for i in self.lst:
k, c = safe_subn(pattern, repl, i[0], *args, **kwargs)
count += c
v, c = safe_subn(pattern, repl, i[1], *args, **kwargs)
count += c
nlst.append([k, v])
self.lst = nlst
return count
# Implement the StateObject protocol from mitmproxy
2016-02-08 01:10:48 +00:00
def get_state(self):
return [tuple(i) for i in self.lst]
2016-02-08 03:16:58 +00:00
def set_state(self, state):
2015-02-27 19:40:17 +00:00
self.lst = [list(i) for i in state]
@classmethod
2016-02-08 03:16:58 +00:00
def from_state(cls, state):
return cls([list(i) for i in state])
2012-06-18 21:42:32 +00:00
class ODictCaseless(ODict):
2012-06-18 21:42:32 +00:00
"""
A variant of ODict with "caseless" keys. This version _preserves_ key
case, but does not consider case when setting or getting items.
"""
2012-06-18 21:42:32 +00:00
def _kconv(self, s):
return s.lower()