From 21c88cf727719f954a1b31dbae5b29e4bf61e4c8 Mon Sep 17 00:00:00 2001 From: Milo Mirate Date: Sat, 30 Apr 2016 12:52:45 -0400 Subject: [PATCH] Make Permissions partially-ordered. Specifically: * P1 <= P2 iff P1 expresses a subset of the permissions expressed by P2. * P1 < P2 iff P1 <= P2 and P1 != P2 * vice versa for P1 >= P2 and P1 > P2 --- discord/permissions.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/discord/permissions.py b/discord/permissions.py index 8d0dbe02a..bc74536c3 100644 --- a/discord/permissions.py +++ b/discord/permissions.py @@ -36,6 +36,18 @@ class Permissions: +-----------+------------------------------------------+ | x != y | Checks if two permissions are not equal. | +-----------+------------------------------------------+ + | x <= y | Checks if a permission is a subset | + | | of another permission. | + +-----------+------------------------------------------+ + | x >= y | Checks if a permission is a superset | + | | of another permission. | + +-----------+------------------------------------------+ + | x < y | Checks if a permission is a strict | + | | subset of another permission. | + +-----------+------------------------------------------+ + | x > y | Checks if a permission is a strict | + | | superset of another permission. | + +-----------+------------------------------------------+ | hash(x) | Return the permission's hash. | +-----------+------------------------------------------+ @@ -63,6 +75,33 @@ class Permissions: def __hash__(self): return hash(self.value) + def is_subset(self, other): + """Returns True if other has the same or fewer permissions as self.""" + if isinstance(other, Permissions): + return (self.value & other.value) == self.value + else: + raise TypeError("cannot compare {} with {}".format(self.__class__.__name__, other.__class__name)) + + def is_superset(self, other): + """Returns True if other has the same or more permissions as self.""" + if isinstance(other, Permissions): + return (self.value | other.value) == self.value + else: + raise TypeError("cannot compare {} with {}".format(self.__class__.__name__, other.__class__name)) + + def is_strict_subset(self, other): + """Returns True if the permissions on other are a strict subset of those on self.""" + return self.is_subset(other) and self != other + + def is_strict_superset(self, other): + """Returns True if the permissions on other are a strict superset of those on self.""" + return self.is_superset(other) and self != other + + __le__ = is_subset + __ge__ = is_superset + __lt__ = is_strict_subset + __gt__ = is_strict_superset + @classmethod def none(cls): """A factory method that creates a :class:`Permissions` with all