matcher.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. class MQTTMatcher:
  2. """Intended to manage topic filters including wildcards.
  3. Internally, MQTTMatcher use a prefix tree (trie) to store
  4. values associated with filters, and has an iter_match()
  5. method to iterate efficiently over all filters that match
  6. some topic name."""
  7. class Node:
  8. __slots__ = '_children', '_content'
  9. def __init__(self):
  10. self._children = {}
  11. self._content = None
  12. def __init__(self):
  13. self._root = self.Node()
  14. def __setitem__(self, key, value):
  15. """Add a topic filter :key to the prefix tree
  16. and associate it to :value"""
  17. node = self._root
  18. for sym in key.split('/'):
  19. node = node._children.setdefault(sym, self.Node())
  20. node._content = value
  21. def __getitem__(self, key):
  22. """Retrieve the value associated with some topic filter :key"""
  23. try:
  24. node = self._root
  25. for sym in key.split('/'):
  26. node = node._children[sym]
  27. except KeyError as err:
  28. raise KeyError(key) from err
  29. else:
  30. if node._content is None:
  31. raise KeyError(key)
  32. return node._content
  33. def __delitem__(self, key):
  34. """Delete the value associated with some topic filter :key"""
  35. lst = []
  36. try:
  37. parent, node = None, self._root
  38. for k in key.split('/'):
  39. parent, node = node, node._children[k]
  40. lst.append((parent, k, node))
  41. except KeyError as err:
  42. raise KeyError(key) from err
  43. else:
  44. if node._content is None:
  45. raise KeyError(key)
  46. node._content = None
  47. # cleanup
  48. for parent, k, node in reversed(lst):
  49. if node._children or node._content is not None:
  50. break
  51. del parent._children[k]
  52. def iter_match(self, topic):
  53. """Return an iterator on all values associated with filters
  54. that match the :topic"""
  55. lst = topic.split('/')
  56. normal = not topic.startswith('$')
  57. def rec(node, i=0):
  58. if i == len(lst):
  59. if node._content is not None:
  60. yield node._content
  61. else:
  62. part = lst[i]
  63. if part in node._children:
  64. yield from rec(node._children[part], i + 1)
  65. if '+' in node._children and (normal or i > 0):
  66. yield from rec(node._children['+'], i + 1)
  67. if '#' in node._children and (normal or i > 0):
  68. content = node._children['#']._content
  69. if content is not None:
  70. yield content
  71. return rec(self._root)