Source code for jam.types.base.boolean

from typing import Union, Any, Tuple
from jam.utils.codec.codable import Codable
from jam.utils.codec.primitives.bools import BooleanCodec
from jam.utils.json.serde import JsonSerde


[docs] class Boolean(Codable, JsonSerde): """ Boolean type that implements the Codable interface. Examples: >>> b = Boolean(True) >>> bool(b) True >>> b.encode() b'\\x01' >>> Boolean.decode_from(b'\\x01') (Boolean(True), 1) """
[docs] def __init__(self, value: bool): """ Initialize a Boolean. Args: value: Python bool value Raises: TypeError: If value is not a bool """ super().__init__(codec=BooleanCodec()) if not isinstance(value, bool): raise TypeError(f"Expected bool, got {type(value)}") self.value = value
[docs] def __bool__(self) -> bool: """Allow using in boolean context.""" return self.value
[docs] def __eq__(self, other: Any) -> bool: """Equal comparison.""" if isinstance(other, Boolean): return self.value == other.value elif isinstance(other, bool): return self.value == other return False
[docs] def __hash__(self) -> int: """Make hashable.""" return hash(self.value)
[docs] def __repr__(self) -> str: """String representation.""" return f"Boolean({self.value})"
[docs] def __bytes__(self) -> bytes: """Bytes representation.""" print(f"Converting {self.value} to bytes = {bytes([1 if self.value else 0])}") return bytes([1 if self.value else 0])
[docs] @staticmethod def decode_from( buffer: Union[bytes, bytearray, memoryview], offset: int = 0 ) -> Tuple[Any, int]: """ Decode a Boolean from a buffer. Args: buffer: Bytes to decode from offset: Starting position in buffer Returns: Tuple of (Boolean instance, bytes read) """ value, size = BooleanCodec().decode_from(buffer, offset) return Boolean(value), size