Coverage for sbe2/schema/types.py: 100%

46 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-29 13:19 +0200

1from .common import FixedLengthElement 

2from .builtin import decimal, decimal32, decimal64, int16, int32, int64, int8, uint16, uint32, uint64, float_, double, char, int_, uint8 

3from .type import Type 

4from .composite import Composite 

5 

6 

7class Types: 

8 """ 

9 This class contains built-in and defined types for the schema. 

10 It includes primitive types, enums, choices, sets, and composites. 

11 """ 

12 

13 def __init__(self): 

14 self._types : dict[str: FixedLengthElement] = {} 

15 self.add(decimal) 

16 self.add(decimal32) 

17 self.add(decimal64) 

18 self.add(int16) 

19 self.add(int32) 

20 self.add(int64) 

21 self.add(int8) 

22 self.add(uint16) 

23 self.add(uint32) 

24 self.add(uint64) 

25 self.add(float_) 

26 self.add(double) 

27 self.add(char) 

28 self.add(int_) 

29 self.add(uint8) 

30 

31 def __len__(self): 

32 """ 

33 Returns the number of types in the collection. 

34  

35 Returns: 

36 int: The number of types. 

37 """ 

38 return len(self._types) 

39 

40 

41 def add(self, type_: FixedLengthElement): 

42 """ 

43 Adds a type to the collection. 

44  

45 Args: 

46 type_ (FixedLengthElement): The type to add. 

47 """ 

48 if type_.name in self._types: 

49 raise ValueError(f"Type '{type_.name}' already exists.") 

50 self._types[type_.name] = type_ 

51 

52 def __getitem__(self, name: str) -> FixedLengthElement: 

53 """ 

54 Retrieves a type by its name. 

55 Args: 

56 name (str): The name of the type to retrieve. 

57 Returns: 

58 FixedLengthElement: The type with the specified name. 

59 Raises: 

60 KeyError: If the type does not exist. 

61 """ 

62 if name not in self._types: 

63 raise KeyError(f"Type '{name}' does not exist.") 

64 return self._types[name] 

65 

66 def get(self, name: str) -> FixedLengthElement | None: 

67 """ 

68 Retrieves a type by its name, returning None if it does not exist. 

69  

70 Args: 

71 name (str): The name of the type to retrieve. 

72  

73 Returns: 

74 FixedLengthElement | None: The type with the specified name or None if not found. 

75 """ 

76 return self._types.get(name) 

77 

78 def __iter__(self): 

79 return iter(self._types.values()) 

80 

81 

82 def get_composite(self, name:str): 

83 com = self[name] 

84 if not isinstance(com, Composite): 

85 raise ValueError(f"Type '{name}' is not composite but '{type(com)}'") 

86 return com 

87 

88 def get_type(self, name:str): 

89 type_ = self[name] 

90 if not isinstance(type_, Type): 

91 raise ValueError(f"Type '{name}' is not type but '{type(type_)}'") 

92 return type_