Index: tools/json_schema_compiler/ordered_dict.py |
diff --git a/tools/json_schema_compiler/ordered_dict.py b/tools/json_schema_compiler/ordered_dict.py |
new file mode 100644 |
index 0000000000000000000000000000000000000000..096d955fe7e7d623ded771201248041bef75cb25 |
--- /dev/null |
+++ b/tools/json_schema_compiler/ordered_dict.py |
@@ -0,0 +1,95 @@ |
+# Copyright (c) 2012 The Chromium Authors. All rights reserved. |
+# Use of this source code is governed by a BSD-style license that can be |
+# found in the LICENSE file. |
+ |
+import operator |
+ |
+class _OrderedDictIterator(object): |
+ def __init__(self, keys, dict_, func): |
+ self._keys = keys |
+ self._dict = dict_ |
+ self._current = 0 |
+ self._func = func |
+ |
+ def __iter__(self): |
+ return self |
+ |
+ def next(self): |
+ if self._current > len(self._keys) - 1: |
+ raise StopIteration |
+ else: |
+ self._current += 1 |
+ key = self._keys[self._current - 1] |
+ return self._func((key, self._dict[key])) |
+ |
+class OrderedDict(object): |
+ """This class is used because it makes sense for the documentation to have the |
+ functions, events, types, and properties in the order they were declared in |
+ the schemas. In Python 2.6, there is no OrderedDict class, so this will be |
+ used. |
+ """ |
+ def __init__(self, items=None): |
+ if items is not None: |
+ self._keys = [i[0] for i in items] |
+ self._dict = dict(items) |
+ else: |
+ self._keys = [] |
+ self._dict = {} |
+ |
+ def __getitem__(self, key): |
+ return self._dict[key] |
+ |
+ def get(self, key, default=None): |
+ if key not in self: |
+ return default |
+ return self[key] |
+ |
+ def __setitem__(self, key, value): |
+ self._dict[key] = value |
+ if key not in self._keys: |
+ self._keys.append(key) |
+ |
+ def values(self): |
+ return [self._dict[k] for k in self._keys] |
+ |
+ def keys(self): |
+ return self._keys |
+ |
+ def iteritems(self): |
+ return _OrderedDictIterator(self._keys, self._dict, lambda x: x) |
+ |
+ def items(self): |
+ return [(k, self._dict[k]) for k in self._keys] |
+ |
+ def update(self, other): |
+ for k, v in other.iteritems(): |
+ self[k] = v |
+ |
+ def __iter__(self): |
+ return _OrderedDictIterator(self._keys, self._dict, operator.itemgetter(0)) |
+ |
+ def __contains__(self, key): |
+ return key in self._keys |
+ |
+ def __repr__(self): |
+ return 'OrderedDict(%s)' % str(self.items()) |
+ |
+ def pop(self, item): |
+ self._keys.remove(item) |
+ return self._dict.pop(item) |
+ |
+ def __delitem__(self, item): |
+ self.pop(item) |
+ |
+ def __eq__(self, other): |
+ if isinstance(other, dict): |
+ return self._dict == other |
+ elif isinstance(other, OrderedDict): |
+ return self._keys == other._keys and self._dict == other._dict |
+ return False |
+ |
+ def __ne__(self, other): |
+ return not (self == other) |
+ |
+ def __len__(self): |
+ return len(self._keys) |