aboutsummaryrefslogtreecommitdiffstats
path: root/netlib/utils.py
diff options
context:
space:
mode:
authorAldo Cortesi <aldo@nullcube.com>2015-04-30 09:04:22 +1200
committerAldo Cortesi <aldo@nullcube.com>2015-04-30 09:04:22 +1200
commit80860229209b4c6eb8384e1bca3cabdbe062fe6e (patch)
treeed0bb19910d81b9b8b8719b4c9fc34a40baa6919 /netlib/utils.py
parentb7a2fc85537dca60fb18d25965289d876bd3bd38 (diff)
downloadmitmproxy-80860229209b4c6eb8384e1bca3cabdbe062fe6e.tar.gz
mitmproxy-80860229209b4c6eb8384e1bca3cabdbe062fe6e.tar.bz2
mitmproxy-80860229209b4c6eb8384e1bca3cabdbe062fe6e.zip
Add a tiny utility class for keeping bi-directional mappings.
Use it in websocket and socks.
Diffstat (limited to 'netlib/utils.py')
-rw-r--r--netlib/utils.py26
1 files changed, 26 insertions, 0 deletions
diff --git a/netlib/utils.py b/netlib/utils.py
index 44bed43a..905d948f 100644
--- a/netlib/utils.py
+++ b/netlib/utils.py
@@ -65,3 +65,29 @@ def getbit(byte, offset):
mask = 1 << offset
if byte & mask:
return True
+
+
+class BiDi:
+ """
+ A wee utility class for keeping bi-directional mappings, like field
+ constants in protocols:
+
+ CONST = BiDi(a=1, b=2)
+ assert CONST.a == 1
+ assert CONST[1] == "a"
+ """
+ def __init__(self, **kwargs):
+ self.names = kwargs
+ self.values = {}
+ for k, v in kwargs.items():
+ self.values[v] = k
+ if len(self.names) != len(self.values):
+ raise ValueError("Duplicate values not allowed.")
+
+ def __getattr__(self, k):
+ if k in self.names:
+ return self.names[k]
+ raise AttributeError("No such attribute: %s", k)
+
+ def __getitem__(self, k):
+ return self.values[k]