transforms: add Enum type

This commit is contained in:
Shiz 2021-06-26 03:39:07 +02:00
parent 7a7a2a90cc
commit 675a01c89f
2 changed files with 19 additions and 4 deletions

View File

@ -8,13 +8,13 @@ from .types.data import Data, data
from .types.num import *
from .types.struct import StructType, Struct
from .types.seq import Arr, Tuple
from .types.transforms import Default, Sized, Ref, Transform, Mapped
from .types.transforms import Default, Sized, Ref, Transform, Mapped, Enum
from .types.io import AlignTo, AlignedTo
__all__ = [x.__name__ for x in {
parse, dump, sizeof, offsetof, default,
parse, dump, sizeof, offsetof, default, to_type,
Context, Type, Stream, Segment,
Wrapper, Default, Sized, Ref, Transform, Mapped,
Wrapper, Default, Sized, Ref, Transform, Mapped, Enum,
AlignTo, AlignedTo,
Data,
Int, Bool, Float,

View File

@ -1,6 +1,7 @@
import os
import errno
from typing import Any, Optional as O, Generic as G, Union as U, TypeVar, Callable, Sequence, Mapping
import enum
from typing import Any, Optional as O, Generic as G, Union as U, TypeVar, Callable, Sequence, Mapping, Type as Ty
from ..core.base import Type, Context, PathElement, PossibleDynamic
from ..core.io import Stream, Segment, Pos
from ..core.meta import Wrapper
@ -194,3 +195,17 @@ class Mapped(G[T, V], Transform[T, V]):
str=str or f'{mapping}[{child}]',
repr=repr or f'<{__name__}.Mapped({child!r}, {mapping!r})>'
)
E = TypeVar('E', bound=enum.Enum)
class Enum(G[T, E], Transform[T, E]):
def __init__(self, enum: Ty[E], child: Type[T]) -> None:
super().__init__(child,
parse=enum,
dump=lambda x: x.value,
context=False,
str=f'{enum.__name__}({child})',
repr=f'{__name__}.Enum({enum!r}, {child!r})',
)