pack¶
Module containing Pack and all its subclasses.
It contains three submodules, and a sub-submodule:
lihzahrd.terraria.utils.pack.pack, with the abstract base class;lihzahrd.terraria.utils.pack.primitive, for single units of data;lihzahrd.terraria.utils.pack.primitive.op, for adding operators to those single units of data;lihzahrd.terraria.utils.pack.composite, for composite data.
pack¶
Submodule for the base Pack abstract class.
- class lihzahrd.terraria.utils.pack.pack.Pack¶
Block of adjacent data in a Terraria save file.
Instances of classes inheriting from this one always have:
read()andwrite()methods to interact with aFileProcessor;a
validate()method to check that the data currently represented makes sense in the context of a Terraria save file.
To better support future Terraria updates, or just to allow more tinkering with the save files, inheritors of
Packshould try to allow as much leeway as it makes sense to in reading and writing values that do not pass validation.- abstractmethod classmethod read(fp: FileProcessor, *, strict: bool = True, **kwargs: Any) PackRead[Self]¶
Read a value from the given
FileProcessor, validate it, then use it to create an instance of this class.- Parameters:
fp – The
FileProcessorto read from.strict – Whether any
ValidationErrorraised should be raised again, or ignored.kwargs – Additional keyword arguments that may be used by implementations to do conditional processing.
- Returns:
A
PackReadinstance with the created instance and validation information.- Raises:
ValidationError – If the read value is invalid and validation is
strict.ReadError – If the value could not be read.
- abstractmethod write(fp: FileProcessor, *, strict: bool = True, **kwargs: Any) PackWrite[Self]¶
Validate the value represented by this instance, then write it to the given
FileProcessor.- Parameters:
fp – The
FileProcessorto write to.strict – Whether any
ValidationErrorraised should be raised again, or ignored.kwargs – Additional keyword arguments that may be used by implementations to do conditional processing.
- Returns:
A
PackWriteinstance with validation information.- Raises:
ValidationError – If the value to write is invalid and validation is
strict.WriteError – If the value could not be written.
- abstractmethod validate(*, strict: bool = True, **kwargs: Any) bool¶
Validate the value represented by this instance.
Note
This method is separate from
read()andwrite(), but can be called by them at their own discretion.- Parameters:
strict – Whether any
ValidationErrorencountered should be re-raised (True) or ignored (False).kwargs – Additional keyword arguments that may be used by implementations to do conditional processing.
- Returns:
Trueif the value is valid,Falseif the value is invalid and validation isn’tstrict.- Raises:
ValidationError – If the value is invalid and validation is
strict.
- exception ValidationError¶
A failure in validation of some kind; if this occurs, it means that the data represented by this instance would not be valid in a Terraria save file.
Tip
You can ignore errors of this type in
read(),write(), andvalidate()by specifyingstrict=Falseas a keyword argument!
- class lihzahrd.terraria.utils.pack.pack.PackRead(instance: Pck, valid: bool)¶
The result of a call to
Pack.read().The generic type
Pckis thePackinstance returning this.Used to bubble up validity information.
Attributes on this class are frozen.
- class lihzahrd.terraria.utils.pack.pack.PackWrite(valid: bool)¶
The result of a call to
Pack.write().The generic type
Pckis thePackinstance returning this.Used to bubble up validity information.
Attributes on this class are frozen.
primitive¶
Submodule for subclasses of Pack directly representing single units of data.
primitive¶
Submodule containing the abstract base class of Pack primitives.
- class lihzahrd.terraria.utils.pack.primitive.primitive.PackPrimitive(value: Value)¶
A
Packrepresenting a single unit of data of generic typeInternalValue.Automatically implements logging, validation, and structured results in
__init__(),read(),write(), andvalidate(), but still requires the inheritor to specify what should be performed in each of those methods by implementing_read(),_write(), and_validate().Tip
To alter the value of PackPrimitives, you can either use the methods specific to the inheriting class, like
set_from_variant(), or directly operate on thevalueattribute, like this:p.value = 67
Via this approach, you can set the value of the PackPrimitive to anything you want, including invalid values!
- value: Value¶
The raw
InternalValuerepresented by this instance.
- _LOG: Logger¶
The
logging.Loggerto use to emit messages about the packing process.Note
logging.Loggeris not created as a global variable because in this way, logging can be filtered by section being processed instead of by class doing the processing, which arguably is more useful in debugging.
- classmethod _validate(value: Value, **kwargs: Any) None¶
Validate the given
InternalValue, raisingValidationErrorif it’s invalid.- Parameters:
value – The
InternalValueto validate.kwargs – Additional keyword arguments that may be used by implementations to do conditional processing.
- Raises:
ValidationError – If
valueis not valid.
- abstractmethod classmethod _read(fp: FileProcessor, **kwargs: Any) Value¶
Read a
InternalValuefrom the givenPacker.Example
The usual implementation of this method will have a body like:
def _read(cls, fp: FileProcessor, **kwargs: Any) -> int: return fp.read_int()
- Parameters:
fp – The
FilePackerto read from.kwargs – Additional keyword arguments that may be used by implementations to do conditional processing.
- Returns:
The read
InternalValue.- Raises:
ReadError – If the value could not be read.
- abstractmethod classmethod _write(fp: FileProcessor, value: Value, **kwargs: Any) None¶
Write the given
InternalValueto the givenPacker.Example
The usual implementation of this method will have a body like:
def _write(cls, fp: FileProcessor, value: int, **kwargs: Any) -> None: fp.write_int(value)
- Parameters:
fp – The
FilePackerto write to.value – The
InternalValueto write.kwargs – Additional keyword arguments that may be used by implementations to do conditional processing.
- Raises:
WriteError – If the value could not be written.
- exception ValidationError(value: Value)¶
A
ValidationErrorin whichInternalValuecan be stored._validate()is expected to raise this kind of error if the value represented by this class is invalid.- value: Value¶
The value which failed validation.
bool¶
Submodule containing processors for boolean types.
- class lihzahrd.terraria.utils.pack.primitive.bool.PackBool(value: Value)¶
A
PackPrimitiveprocessing aBOOLasbool.
int¶
Submodule containing processors for integer types.
- class lihzahrd.terraria.utils.pack.primitive.int.PackInteger(value: Value)¶
A
PackPrimitiveprocessing integers.On validation, it ensures that the represented value is between
VALUE_MINandVALUE_MAX, and raisesOverflowErrorotherwise.- exception OverflowError(value: Value)¶
The processed value is out of representable range.
- class lihzahrd.terraria.utils.pack.primitive.int.PackSByte(value: Value)¶
A
PackIntegerprocessing aSBYTEasint.
- class lihzahrd.terraria.utils.pack.primitive.int.PackByte(value: Value)¶
A
PackIntegerprocessing aBYTEasint.
- class lihzahrd.terraria.utils.pack.primitive.int.PackShort(value: Value)¶
A
PackIntegerprocessing aSHORTasint.
- class lihzahrd.terraria.utils.pack.primitive.int.PackUShort(value: Value)¶
A
PackIntegerprocessing aUSHORTasint.
- class lihzahrd.terraria.utils.pack.primitive.int.PackInt(value: Value)¶
A
PackIntegerprocessing aINTasint.
- class lihzahrd.terraria.utils.pack.primitive.int.PackUInt(value: Value)¶
A
PackIntegerprocessing aUINTasint.
- class lihzahrd.terraria.utils.pack.primitive.int.PackLong(value: Value)¶
A
PackIntegerprocessing aLONGasint.
- class lihzahrd.terraria.utils.pack.primitive.int.PackULong(value: Value)¶
A
PackIntegerprocessing aULONGasint.
float¶
Submodule containing processors for floating-point numeric types.
- class lihzahrd.terraria.utils.pack.primitive.float.PackFloating(value: Value)¶
A
PackPrimitiveprocessing floating-point numeric types.
- class lihzahrd.terraria.utils.pack.primitive.float.PackFloat(value: Value)¶
A
PackFloatingprocessing aFLOATasfloat.
- class lihzahrd.terraria.utils.pack.primitive.float.PackDouble(value: Value)¶
A
PackDoubleprocessing aFLOATasfloat.
coordinates¶
Submodule containing processors for Coordinates.
- class lihzahrd.terraria.utils.pack.primitive.coordinates.PackCoordinatesInt(value: Value)¶
A
PackPrimitiveprocessing a pair ofintasCoordinates.- exception OverflowError(value: Value)¶
The bounds are not within the representable range.
rectangle¶
Submodule containing processors for Rectangle.
date¶
Submodule containing processors for datetime.
- class lihzahrd.terraria.utils.pack.primitive.date.PackDatetime(value: Value)¶
A
PackPrimitiveprocessing adatetime.
bytes¶
Submodule containing processors for raw bytes.
- class lihzahrd.terraria.utils.pack.primitive.bytes.PackUnknown(value: Value)¶
A
PackPrimitiveprocessing blocks of rawbytes.When this class starts a
read(), it keeps on reading until it reaches the address specified by theuntilkeyword argument.If instance of this class contain a non-zero amount of bytes, it will fail validation with
UnknonwnBytesError(as that probably means that something went wrong during the parsing of the corresponding save file section), unless theacceptablekeyword argument isTrue.Tip
This behavior can be useful when you want to deliberately skip processing some sections of a save file, because for example they were loaded from a cache. This behavior can be useful when you want to deliberately skip processing some sections of a save file, because for example they were loaded from a cache.
- Parameters:
until – The byte offset at which to stop reading.
acceptable – If
True, noUnknownBytesErrorwill be raised on validation.
- exception UnknownBytesError(value: Value)¶
Unknown bytes are present.
str¶
Submodule containing processors for strings.
- class lihzahrd.terraria.utils.pack.primitive.str.PackStrFixed(value: Value)¶
A
PackPrimitiveprocessing fixed-length strings.On validation, it ensures that the represented value is exactly
DATA_LENbytes long, and raisesInvalidLengthErrorotherwise.- exception InvalidLengthError(value: Value)¶
The string is not of the required length.
- class lihzahrd.terraria.utils.pack.primitive.str.PackStrVariable(value: Value)¶
A
PackPrimitiveprocessing variable-length strings.
uuid_¶
Submodule containing processors for UUID.
- class lihzahrd.terraria.utils.pack.primitive.uuid_.PackUUID(value: Value)¶
A
PackPrimitiveprocessing aUUID.
enumeration¶
Submodule containing processors for classes in enum.
- class lihzahrd.terraria.utils.pack.primitive.enumeration.PackEnum(value: Value)¶
A
PackPrimitivewhere all the valid values are known at class definition time, and are represented by theEnumValidValue, whose value is of the generic typeInternalValue.On validation, it checks that the represented value is a valid value of
ENUM, and raisesUnknownVariantErrorotherwise.- classmethod from_variant(variant: ValidValue) Self¶
Create an instance of this class from an
Enumvariant.- Parameters:
variant – The variant to use to create the instance.
- Returns:
The created instance.
- classmethod from_name(key) Self¶
Create an instance of this class from an
Enumvariant’sname.- Parameters:
key – The
nameto use to create the instance.- Returns:
The created instance.
- variant() ValidValue¶
Convert this instance to the corresponding
Enumvariant.- Returns:
The created variant.
- Raises:
ValueError – If the value does not correspond to any enum variant.
- set_from_variant(variant: ValidValue) None¶
Set the value of this class instance to the value of the given variant.
- Parameters:
variant – The variant to use to set the value.
- class lihzahrd.terraria.utils.pack.primitive.enumeration.PackFlags(value: Value)¶
A
PackPrimitivewhere all the valid values are known at class definition time, and are represented by theFlagValidValue, whose value is of the generic typeInternalValue.On validation, it checks that the represented value is a valid value of
FLAGS, and raisesUnknownVariantErrorotherwise.- exception UnknownFlagsError(value: Value)¶
The specified value is not among the known values
FLAGScan take.
- classmethod from_variant(variant: ValidValue) Self¶
Create an instance of this class from a
Flagvariant.- Parameters:
variant – The variant to use to create the instance.
- Returns:
The created instance.
- variant() ValidValue¶
Convert this instance to the corresponding
Flagvariant.- Returns:
The created variant.
- Raises:
ValueError – If the value does not correspond to any enum variant.
op¶
Module containing mixins to add various operators to classes inheriting from PackPrimitive.
Example
To allow instances of a class inheriting from PackInt to behave like regular int would, you can mixin OpInteger:
class WorldRevision(OpInteger, PackInt):
...
Allowing for code like the following:
p1: WorldRevision = WorldRevision.read(fp).instance
p2: WorldRevision = WorldRevision.read(fp).instance
p3: WorldRevision = p1 + p2
assert p3.value == p1.value + p2.value
equality¶
Submodule for OpEquality.
boolean¶
Submodule for OpBoolean.
- class lihzahrd.terraria.utils.pack.primitive.op.boolean.OpBoolean(value: Value)¶
Extension of
OpEqualitywhich adds boolean operators based onvalue.
collection¶
Submodule for OpCollection.
- class lihzahrd.terraria.utils.pack.primitive.op.collection.OpCollection(value: Value)¶
Extension of
OpEqualitywhich adds collection operators based onvalue.
comparison¶
Submodule for OpComparison.
number¶
Submodule for OpNumber.
- class lihzahrd.terraria.utils.pack.primitive.op.number.OpNumber(value: Value)¶
Extension of
OpComparisonwhich adds number operators based onvalue.Note
__pow__()and__ipow__()are not implemented due to ambiguity regarding how to handle themoduloparameter.
integer¶
Submodule for OpInteger.
floating¶
Submodule for OpFloating.
composite¶
Submodule for subclasses of Pack representing composite sections of data, composed of multiple underlying sub- Pack.
composite¶
Submodule for PackComposite.
- class lihzahrd.terraria.utils.pack.composite.composite.PackComposite(*args: Pack, **kwargs)¶
A
Packrepresenting an ordered and fixed-length set of heterogenousPackitems.Automatically implements
read(),write(), andvalidate()with logging, validation, and structured results, but requires the inheritor to define the fields that instances should contain, and specify the order they should be processed to via_fields().- abstractmethod __init__(*args: Pack, **kwargs)¶
Create a new instance of the
PackCompositeby determining the fields it will have with the given kwargs, then by setting the value of each to the arg with the same index.For instances to have correct attribute suggestions in IDEs, the
__init__()method of eachPackCompositemust be overridden.The override should define a new instance-level attribute for each field, annotating it with the type of the field value, and assigning to it the value
Ellipsis(which will be ignored byField).Example
From
FileMetadata:@override def __init__(self, *args: Pack, **kwargs): self.version: PackFileVersion = ... self.signature: PackFileSignature = ... self.kind: PackFileKind = ... self.revision: PackFileRevision = ... self.flags: PackFileFlags = ... super().__init__(*args, **kwargs)
- class Field(ty: type[Value])¶
A descriptor for one of the
Packvalues making up the composite object.Necessary to allow
read()to determine the class to callread()on.If a field is attempted to be set to
Ellipsis, the action is ignored; this is used to make instance-level type hinting prevail over the class-level descriptor access on IDEs.
- abstractmethod classmethod _fields(**kwargs) list[Field[Self, Pack]]¶
Get a
listof the fields that should be processed, in the order they should be processed.Warning
Getters of the included properties must have a correct type annotation!
- Parameters:
kwargs – Additional keyword arguments that may be used by implementations to do conditional processing.
- Returns:
The
property()that should be validated, read, or written, in the order these operations should be done.
- _LOG = <Logger lihzahrd.terraria.utils.pack.composite.composite (WARNING)>¶
The
logging.Loggerto use to emit messages about the packing process.
count_array¶
Submodule for PackCountArray.
- class lihzahrd.terraria.utils.pack.composite.count_array.PackCountArray(items: list[Item])¶
A
Packrepresenting an ordered and variable-length set of homogeneousPackitems.The serialization it expects is:
Item count
Item #1
Item #2
…
Automatically implements
read(),write(), andvalidate()with logging, validation, and structured results, but it requires the inheritor to define the way to read or write the item count by implementing_read_count()and_write_count().On validation, if
MAX_COUNTis notNone, it ensures that the collection represented by this object is not larger thanMAX_COUNT, and raisesLimitExceededErrorotherwise.- abstractmethod classmethod _read_count(fp: FileProcessor) int¶
Read the amount of items to subsequently read to the collection.
- Parameters:
fp – The
lihzahrd.terraria.utils.file_processor.FileProcessorto read from.- Returns:
The number of items to read to the collection.
- abstractmethod classmethod _write_count(fp: FileProcessor, count: int) None¶
Write the amount of items to subsequently write to the collection.
- Parameters:
fp – The
lihzahrd.terraria.utils.file_processor.FileProcessorto write to.àcount – The count of items in the collection to write.
flag_array¶
Submodule for PackFlagArray.
- class lihzahrd.terraria.utils.pack.composite.flag_array.PackFlagArray(items: list[Item])¶
A
Packrepresenting an ordered and variable-length set of homogeneousPackitems.The serialization it expects is:
Boolean
True(“there is an item afterward”)Item #1
Boolean
True(“there is an item afterward”)Item #2
Boolean
False(“items have ended”)
Automatically implements
read(),write(), andvalidate()with logging, validation, and structured results.