From 8019ecd16ca30afbc52045643fa0aa092ead0e6f Mon Sep 17 00:00:00 2001 From: Helmut Grohne Date: Wed, 13 Aug 2025 11:11:53 +0200 Subject: support slicing an IDMapping --- linuxnamespaces/idmap.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/linuxnamespaces/idmap.py b/linuxnamespaces/idmap.py index f66456d..edd823c 100644 --- a/linuxnamespaces/idmap.py +++ b/linuxnamespaces/idmap.py @@ -74,6 +74,21 @@ class IDMapping: """Construct an identity mapping for the given identifier.""" return cls(idn, idn, count) + def __getitem__(self, key: int | slice) -> typing.Self: + """Return an entry or slice of the allocated mapping.""" + if isinstance(key, int): + key = slice(key, None, None) + if not isinstance(key, slice): + raise TypeError("slicing an IDMapping requires an int or slice") + start, stop, step = key.indices(self.count) + if step != 1: + raise ValueError("IDMapping cannot slice non-trivial steps") + if start >= stop: + raise ValueError("slicing IDMapping resulted in empty mapping") + return self.__class__( + self.innerstart + start, self.outerstart + start, stop - start + ) + class IDAllocation: """This represents a subset of IDs (user or group). It can be used to -- cgit v1.2.3