Stores the minimum and maximum widths (in characters) required to render an object.
| 9 | |
| 10 | |
| 11 | class Measurement(NamedTuple): |
| 12 | """Stores the minimum and maximum widths (in characters) required to render an object.""" |
| 13 | |
| 14 | minimum: int |
| 15 | """Minimum number of cells required to render.""" |
| 16 | maximum: int |
| 17 | """Maximum number of cells required to render.""" |
| 18 | |
| 19 | @property |
| 20 | def span(self) -> int: |
| 21 | """Get difference between maximum and minimum.""" |
| 22 | return self.maximum - self.minimum |
| 23 | |
| 24 | def normalize(self) -> "Measurement": |
| 25 | """Get measurement that ensures that minimum <= maximum and minimum >= 0 |
| 26 | |
| 27 | Returns: |
| 28 | Measurement: A normalized measurement. |
| 29 | """ |
| 30 | minimum, maximum = self |
| 31 | minimum = min(max(0, minimum), maximum) |
| 32 | return Measurement(max(0, minimum), max(0, max(minimum, maximum))) |
| 33 | |
| 34 | def with_maximum(self, width: int) -> "Measurement": |
| 35 | """Get a RenderableWith where the widths are <= width. |
| 36 | |
| 37 | Args: |
| 38 | width (int): Maximum desired width. |
| 39 | |
| 40 | Returns: |
| 41 | Measurement: New Measurement object. |
| 42 | """ |
| 43 | minimum, maximum = self |
| 44 | return Measurement(min(minimum, width), min(maximum, width)) |
| 45 | |
| 46 | def with_minimum(self, width: int) -> "Measurement": |
| 47 | """Get a RenderableWith where the widths are >= width. |
| 48 | |
| 49 | Args: |
| 50 | width (int): Minimum desired width. |
| 51 | |
| 52 | Returns: |
| 53 | Measurement: New Measurement object. |
| 54 | """ |
| 55 | minimum, maximum = self |
| 56 | width = max(0, width) |
| 57 | return Measurement(max(minimum, width), max(maximum, width)) |
| 58 | |
| 59 | def clamp( |
| 60 | self, min_width: Optional[int] = None, max_width: Optional[int] = None |
| 61 | ) -> "Measurement": |
| 62 | """Clamp a measurement within the specified range. |
| 63 | |
| 64 | Args: |
| 65 | min_width (int): Minimum desired width, or ``None`` for no minimum. Defaults to None. |
| 66 | max_width (int): Maximum desired width, or ``None`` for no maximum. Defaults to None. |
| 67 | |
| 68 | Returns: |
no outgoing calls