### Typed Example Usage Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md Demonstrates how to extract typed values using get() and getTyped() with DSL field optics. ```java Typed player = ...; Typed name = player.getTyped(DSL.field("name", DSL.string())); String nameValue = player.get(DSL.field("name", DSL.string())); ``` -------------------------------- ### Example: Adding a Schema Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Demonstrates how to create a DataFixerBuilder and add a new schema with custom type registration logic. ```java DataFixerBuilder builder = new DataFixerBuilder(110); Schema v100 = builder.addSchema(100, (key, parent) -> new Schema(key, parent) { @Override public Map> registerTypes(Schema schema) { // register types for this version } } ); ``` -------------------------------- ### Example: Adding a Data Fix Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Shows how to register a custom DataFix with the builder, including defining the makeRule for transformations. ```java builder.addFixer(new DataFix(schema110, true) { @Override protected TypeRewriteRule makeRule() { return fixTypeEverywhere("rename_field", oldType, newType, ops -> obj -> { // transformation logic }); } }); ``` -------------------------------- ### Field-Based Transformation Example Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md An example demonstrating how to perform field-based transformations on typed data using Optics. This includes accessing and modifying specific fields within a schema. ```APIDOC ## Example: Field-Based Transformation ```java // Schema defines a Player type with fields: name, uuid, health Schema schema = ...; Type playerType = schema.getType(() -> "Player"); // Create typed value Dynamic input = ...; Typed player = playerType.readTyped(input); // Access field OpticFinder nameFinder = DSL.field("name", DSL.string()); String oldName = player.get(nameFinder); // Modify field Typed updated = player.set(nameFinder, "NewName"); // Nested field access OpticFinder healthFinder = DSL.field("health", DSL.intType()); int health = player.get(healthFinder); ``` ``` -------------------------------- ### Example Lens Usage Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md Demonstrates how to create a Lens for a Player object to access and modify its name. This requires a Player class with getName and withName methods. ```java Lens nameLens = Optics.lens( Player::getName, (player, name) -> player.withName(name) ); ``` -------------------------------- ### Basic DataFixer Setup and Upgrade Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/examples.md Demonstrates how to set up DataFixerUpper with multiple schemas and apply a data fix to upgrade data from an older version to a newer one. This is useful for migrating data when your application's data structure evolves. ```java import com.mojang.datafixers.*; import com.mojang.datafixers.schemas.Schema; import com.mojang.serialization.Dynamic; import com.mojang.serialization.JsonOps; import com.google.gson.JsonElement; public class DataFixerSetup { public static void main(String[] args) { // Create builder for current version DataFixerBuilder builder = new DataFixerBuilder(110); // Version 100 schema Schema schema100 = builder.addSchema(100, (key, parent) -> new Schema(key, parent) { @Override protected Map> registerTypes(Schema schema) { return Map.ofEntries( Map.entry("Player", () -> DSL.record( DSL.named("name", DSL.string()), DSL.named("uuid", DSL.string()), DSL.named("health", DSL.floatType()) ) ) ); } } ); // Version 110 schema with additional field Schema schema110 = builder.addSchema(110, (key, parent) -> new Schema(key, parent) { @Override protected Map> registerTypes(Schema schema) { return Map.ofEntries( Map.entry("Player", () -> DSL.record( DSL.named("name", DSL.string()), DSL.named("uuid", DSL.string()), DSL.named("health", DSL.floatType()), DSL.named("experience", DSL.intType()) // New field ) ) ); } } ); // Register fix to add default experience value builder.addFixer(new DataFix(schema110, false) { @Override protected TypeRewriteRule makeRule() { return fixTypeEverywhere("add_experience_field", getInputSchema().getType(() -> "Player"), getOutputSchema().getType(() -> "Player"), ops -> player -> { // In real code, would manipulate the player object // Here we just return it unchanged; field defaults to 0 return player; } ); } }); // Build and optimize DataFixerBuilder.Result result = builder.build(); DataFixer fixer = result.fixer(); // Use fixer to upgrade data JsonElement oldPlayerData = /* ... */; Dynamic input = new Dynamic<>(JsonOps.INSTANCE, oldPlayerData); Dynamic upgraded = fixer.update( () -> "Player", input, 100, // old version 110 // new version ); JsonElement result = upgraded.getValue(); } } ``` -------------------------------- ### Example DataFix fixTypeEverywhere Rule Implementation Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Example implementation of a custom data fix rule using fixTypeEverywhere. This demonstrates how to define a transformation for a specific data type within a DataFix subclass. ```java protected TypeRewriteRule makeRule() { return fixTypeEverywhere("rename_foo_to_bar", getInputSchema().getType(() -> "MyData"), getOutputSchema().getType(() -> "MyData"), ops -> oldObj -> { // Transform oldObj to new format return transformedObj; } ); } ``` -------------------------------- ### Recursive Type Setup in Schema Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md Configure recursive types within a custom Schema by registering type families with self-references using DSL.id(). This example shows recursive setup for ItemStack and Entity. ```java public class MySchema extends Schema { // Register recursive type family private static final int ITEM_STACK_ID = 0; private static final int ENTITY_ID = 1; @Override public Schema(int versionKey, Schema parent) { super(versionKey, parent); // recursiveTypes are automatically populated in parent constructor } @Override protected Map> registerTypes(Schema schema) { return Map.ofEntries( Map.entry("ItemStack", () -> DSL.record( DSL.field("id", DSL.id(ITEM_STACK_ID)), // Self-reference DSL.field("count", DSL.byteType()) ) ), Map.entry("Entity", () -> DSL.record( DSL.field("passengers", DSL.list(DSL.id(ENTITY_ID)) // Self-reference ) ) ) ); } } ``` -------------------------------- ### Use FieldFinder to Get and Set Struct Field Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md Example showing how to use a FieldFinder to retrieve and update a specific field within a struct type. This demonstrates direct field access and modification. ```Java Type pointType = schema.getType(() -> "Point"); FieldFinder xField = new FieldFinder("x", DSL.intType()); Typed point = ...; int x = point.get(xField); Typed updated = point.set(xField, x + 1); ``` -------------------------------- ### Codec Usage Example Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/examples.md Demonstrates encoding a Location object to JSON and decoding a JSON string back into a Location object using the defined codec. Handles potential decoding errors. ```java import com.mojang.serialization.DataResult; import com.mojang.serialization.JsonOps; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import java.util.List; // Assuming Location and Entity classes with their CODEC definitions are available public class CodecUsage { public static void main(String[] args) { Location loc = new Location(100.5, 64.0, 200.5); // Encode to JSON DataResult encoded = Location.CODEC.encodeStart( JsonOps.INSTANCE, loc ); // Decode from JSON JsonElement json = JsonParser.parseString( "{\"x\": 100.5, \"y\": 64.0, \"z\": 200.5}" ); DataResult decoded = Location.CODEC.decode( JsonOps.INSTANCE, json ); Location result = decoded.resultOrPartial(System.err::println) .map(p -> p.getFirst()) // Extract Location from Pair .orElse(loc); } } ``` -------------------------------- ### Type Template Definition Example Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md Demonstrates the pattern for defining Type Templates within the registerTypes method using DSL for records, fields, and lists. ```java @Override protected Map> registerTypes(Schema schema) { return schema.registerTypes(schema, Map.ofEntries( Map.entry("MyType", () -> DSL.record( DSL.field("field1", DSL.string()), DSL.field("field2", DSL.intType()), DSL.field("optionalField", DSL.optional(DSL.doubleType())) ) ), Map.entry("ItemStack", () -> DSL.record( DSL.field("id", DSL.intType()), DSL.field("count", DSL.byteType()), DSL.field("tag", DSL.remainderType()) // Catch-all for extra fields ) ), Map.entry("ListExample", () -> DSL.list(DSL.string()) ) ) ); } ``` -------------------------------- ### Example DataFix fixTypeEverywhereTyped Rule Implementation Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Example implementation of a custom data fix rule using fixTypeEverywhereTyped. This shows how to access the Typed context, including DynamicOps, for more complex transformations. ```java protected TypeRewriteRule makeRule() { return fixTypeEverywhereTyped("add_default_field", getInputSchema().getType(() -> "Config"), getOutputSchema().getType(() -> "Config"), typed -> { // typed has access to ops and the actual Dynamic value return typed; // possibly modified } ); } ``` -------------------------------- ### Field-Based Transformation Example Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md Demonstrates how to use Optics to access and modify fields within a typed data structure. This is useful for targeted updates to specific data points. ```java // Schema defines a Player type with fields: name, uuid, health Schema schema = ...; Type playerType = schema.getType(() -> "Player"); // Create typed value Dynamic input = ...; Typed player = playerType.readTyped(input); // Access field OpticFinder nameFinder = DSL.field("name", DSL.string()); String oldName = player.get(nameFinder); // Modify field Typed updated = player.set(nameFinder, "NewName"); // Nested field access OpticFinder healthFinder = DSL.field("health", DSL.intType()); int health = player.get(healthFinder); ``` -------------------------------- ### Process Data in Batches Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md For bulk transformations, process data in batches to manage memory effectively. This example demonstrates loading and transforming a batch of 1000 items. ```java // Process in batches to manage memory List> batch = loadBatch(1000); List> transformed = batch.stream() .map(item -> fixer.update(typeRef, item, oldVersion, newVersion)) .collect(Collectors.toList()); ``` -------------------------------- ### Codec with Lifecycle Metadata Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md Apply lifecycle metadata to an existing codec. Use `.stable()` for stable codecs or `.deprecated(version)` to mark a codec as deprecated starting from a specific version. ```java Codec stableCodec = codec.stable(); ``` ```java Codec deprecatedCodec = codec.deprecated(5); ``` -------------------------------- ### Get or Create Codec Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md Retrieves the Codec associated with this type. If a Codec has not been created yet, it will be generated and cached for future use. ```Java public Codec codec() ``` -------------------------------- ### Transform List to Map in DataFix Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/examples.md Example of a structural transformation, converting an enchantment list to a map. This demonstrates converting complex data structures. ```java public class ListToMapTransformFix extends DataFix { public ListToMapTransformFix(Schema outputSchema) { super(outputSchema, true); } @Override protected TypeRewriteRule makeRule() { return fixTypeEverywhere("convert_enchantments_list_to_map", getInputSchema().getType(() -> "ItemStack"), getOutputSchema().getType(() -> "ItemStack"), ops -> itemStack -> { // Convert old list-based enchantments to new map-based format List oldList = extractEnchantmentList(itemStack); Map newMap = oldList.stream() .collect(Collectors.toMap( Enchantment::getName, Enchantment::getLevel )); return applyEnchantmentMap(itemStack, newMap); } ); } } ``` -------------------------------- ### Register Main Types in Schema Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md This example demonstrates how to override the registerTypes method in a Schema subclass to define main types using DSL factory methods. It returns a map of type names to their corresponding template suppliers. ```java protected Map> registerTypes(Schema schema, Map> types, ...) @Override protected Map> registerTypes(Schema schema) { return schema.registerTypes(schema, Map.ofEntries( Map.entry("Player", () -> DSL.record( DSL.named("name", DSL.string()), DSL.named("uuid", DSL.string()), DSL.named("inventory", DSL.list(DSL.id(itemTypeId))) )) ) ); } ``` -------------------------------- ### Create a Lens Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md Use this factory method to create a Lens, which focuses on a single, always-present field. It allows for both getting and setting the field's value. ```java static Lens lens(Function getter, BiFunction setter) ``` -------------------------------- ### Use NamedChoiceFinder to Get Typed Value Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md Example demonstrating how to use a NamedChoiceFinder to retrieve a typed value from a union type. This is useful for accessing specific options within a sum type. ```Java // For a type with multiple options: "dog" -> Dog, "cat" -> Cat NamedChoiceFinder finder = NamedChoiceFinder.namedChoice("dog", DOG_TYPE); Typed animal = ...; Typed dog = animal.getTyped(finder); ``` -------------------------------- ### Asynchronous Optimization with Datafixerupper Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/examples.md Shows how to set up and initiate asynchronous optimization for specific data types using Datafixerupper. This can improve query performance after the optimization completes. ```java public class OptimizationUsage { public static void main(String[] args) throws Exception { DataFixerBuilder builder = new DataFixerBuilder(110); // ... add schemas and fixes ... DataFixerBuilder.Result result = builder.build(); // Define types to optimize Set importantTypes = Set.of( () -> "Player", () -> "ItemStack", () -> "Entity", () -> "Chunk" ); // Start async optimization System.out.println("Starting optimization..."); CompletableFuture optimization = result.optimize( importantTypes, ForkJoinPool.commonPool() ); // Can use fixer immediately, but first queries on optimized types will wait DataFixer fixer = result.fixer(); // Do other work while optimizing... System.out.println("Fixer ready, optimization in progress..."); // Wait for optimization to complete optimization.join(); System.out.println("Optimization complete!"); // Now all queries will be fast Dynamic data = /* ... */; Dynamic upgraded = fixer.update( () -> "Player", data, 100, 110 ); } } ``` -------------------------------- ### Dynamic Navigation with JSON Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/examples.md Demonstrates how to create a Dynamic object from JSON, navigate nested structures, and update values using Datafixerupper. ```java public class DynamicNavigation { public static void main(String[] args) { // Create a Dynamic from JSON JsonElement json = JsonParser.parseString( "{\"player\": {\"name\": \"Steve\", \"health\": 20.0}}" ); Dynamic root = new Dynamic<>(JsonOps.INSTANCE, json); // Navigate nested structure OptionalDynamic playerObj = root.get("player"); OptionalDynamic name = playerObj .flatMap(p -> p.asMap() .map(m -> m.get(new Dynamic<>(JsonOps.INSTANCE, JsonOps.INSTANCE.createString("name"))))) .flatMap(d -> d.asString()); System.out.println("Player name: " + name.result()); // Optional // Update nested value Dynamic updated = root.updateMapValues(entry -> { Dynamic key = entry.getFirst(); Dynamic val = entry.getSecond(); if ("player".equals(key.asString().result().orElse(""))) { return Pair.of(key, val.map(v -> // Update nested map v )); } return entry; }); } } ``` -------------------------------- ### Production Logging Settings Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md Configure DataFixer and serialization packages to INFO and WARN levels respectively for production environments to reduce overhead. ```xml ``` -------------------------------- ### Get Operations Handler Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Retrieves the DynamicOps handler associated with this Dynamic instance. ```java public DynamicOps getOps() ``` -------------------------------- ### Version Key Encoding and Utilities Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md Explains how version keys are encoded and provides utility methods for creating and extracting version information. ```java // Version keys are encoded as: (version << 16) | subVersion // Utility methods: // - DataFixUtils.makeKey(version) → key with subVersion 0 // - DataFixUtils.makeKey(version, subVersion) → full key // - DataFixUtils.getVersion(key) → extract major version // - DataFixUtils.getSubVersion(key) → extract sub-version ``` -------------------------------- ### Pre-compilation Optimization with Async Warm-up Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md Use this to warm up the DataFixerUpper with required types before the first queries. This can improve performance by compiling rules asynchronously. ```java DataFixerBuilder builder = ...; DataFixerBuilder.Result result = builder.build(); Set requiredTypes = Set.of( () -> "Player", () -> "ItemStack", () -> "Entity" ); // Warm up with async optimization CompletableFuture optimizationDone = result.optimize( requiredTypes, ForkJoinPool.commonPool() // or custom executor ); // Can use fixer immediately, but first queries will block on compilation DataFixer fixer = result.fixer(); ``` -------------------------------- ### Get Wrapped Value Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Retrieves the underlying value wrapped by the Dynamic object. ```java public T getValue() ``` -------------------------------- ### Get List Elements Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Extracts all elements from a list-like value as Dynamic objects. Returns a DataResult. ```java public DataResult>> getList() ``` -------------------------------- ### Enable DEBUG Logging via Configuration Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/errors.md Configure log levels to DEBUG for DatafixerUpper and Serialization packages using logging configuration files like logback.xml or log4j2.xml. ```xml ``` -------------------------------- ### Get Schema Version Key Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md The getVersionKey() method returns the encoded version key for this schema. ```java public int getVersionKey() ``` -------------------------------- ### Typed Get Value by Optic Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md Extracts a value from the Typed object using an OpticFinder to specify the path. ```java public FT get(OpticFinder optic) ``` -------------------------------- ### build() Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Creates the final optimized DataFixer. The returned Result object wraps the fixer and provides async optimization. ```APIDOC ## build() ### Description Creates the final optimized DataFixer. The returned Result object wraps the fixer and provides async optimization. ### Method ```java public Result build() ``` ### Returns `DataFixerBuilder.Result` — A result wrapper ``` -------------------------------- ### Get Parent Schema Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md The getParent() method returns the parent schema of the current schema, if one exists. ```java public Schema getParent() ``` -------------------------------- ### Build DataFixer and Upgrade Data Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/README.md Builds the DataFixer runtime engine and uses it to upgrade 'Player' data from version 100 to 110. This demonstrates the final step of applying defined fixes to actual data. ```java DataFixer fixer = builder.build().fixer(); Dynamic upgraded = fixer.update( () -> "Player", input, 100, // old version 110 // new version ); ``` -------------------------------- ### Get Focused Element Type in Source Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md Retrieves the type 'A' of the focused element(s) within the source structure of a TypedOptic. ```java public Type aType() ``` -------------------------------- ### Lifecycle Management: withLifecycle() Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Attaches custom lifecycle information to a codec. ```APIDOC ## Lifecycle Management: withLifecycle() ### `default Codec withLifecycle(Lifecycle lifecycle)` Attaches stability information to codec. This allows for more granular control over the lifecycle status of a codec. ``` -------------------------------- ### Build DataFixer and Optimize Types Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Builds a DataFixer instance and asynchronously pre-compiles rewrite rules for specified types to improve performance. This is useful for optimizing frequently accessed data types. ```java DataFixerBuilder.Result result = builder.build(); Set types = Set.of( () -> "Player", () -> "ItemStack" ); result.optimize(types, ForkJoinPool.commonPool()) .thenRun(() -> System.out.println("Optimization complete")) .join(); DataFixer fixer = result.fixer(); ``` -------------------------------- ### Get Raw Type by Reference Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md The getTypeRaw() method retrieves a type by its reference without unwrapping recursive types. ```java public Type getTypeRaw(DSL.TypeReference type) ``` -------------------------------- ### Rename Field in DataFix Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/examples.md Example of renaming a field within an Entity type. This uses a typed approach for structural manipulation. ```java public class RenameFieldFix extends DataFix { public RenameFieldFix(Schema outputSchema) { super(outputSchema, false); } @Override protected TypeRewriteRule makeRule() { return fixTypeEverywhereTyped("rename_name_to_display_name", getInputSchema().getType(() -> "Entity"), getOutputSchema().getType(() -> "Entity"), typed -> { // This approach works with typed structures // Real implementation would use optics to extract, transform, and rebuild return typed; } ); } } ``` -------------------------------- ### DataResult: Get Result or Throw Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Retrieves the successful result, throwing a custom exception or a default IllegalStateException if the DataResult is not successful. ```java R getOrThrow(Function exceptionSupplier) throws E R getOrThrow() throws IllegalStateException ``` -------------------------------- ### Get Focused Element Type in Target Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md Retrieves the type 'B' of the focused element(s) within the target structure of a TypedOptic. ```java public Type bType() ``` -------------------------------- ### Register a DataFixer Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md Configure and build a DataFixer by adding schemas and custom DataFix implementations. ```java DataFixerBuilder builder = new DataFixerBuilder(100); Schema schema100 = builder.addSchema(100, (key, parent) -> new Schema(key, parent) { @Override protected Map> registerTypes(Schema schema) { return // ... } }); builder.addFixer(new MyDataFix(schema100, false)); ``` -------------------------------- ### Typed Get Typed by Optic Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md Extracts a Typed value from the Typed object using an OpticFinder, maintaining the full context. ```java public Typed getTyped(OpticFinder optic) ``` -------------------------------- ### Configure SLF4J Logging with logback.xml Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md Set specific logging levels for DataFixerUpper and serialization packages. The root logger is set to INFO, with DataFixer debug logging enabled. ```xml %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n ``` -------------------------------- ### Get Registered Type Names Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md The types() method returns a set containing the names of all registered types within this schema. ```java public Set types() ``` -------------------------------- ### Type Configuration Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Methods for configuring and wrapping types. ```APIDOC ## Type Configuration ### named() ```java static TypeTemplate named(String name, TypeTemplate element) static Type> named(String name, Type element) ``` Wraps a type with a name, useful for struct fields. ### constType() ```java static TypeTemplate constType(Type type) ``` Wraps a Type as a TypeTemplate for composition. ### check() ```java static TypeTemplate check(String name, int index, TypeTemplate element) ``` Adds a check constraint to a type at a specific index in choice/sum types. ### hook() ```java static TypeTemplate hook(TypeTemplate template, Hook.HookFunction preRead, Hook.HookFunction postWrite) static Type hook(Type type, Hook.HookFunction preRead, Hook.HookFunction postWrite) ``` Attaches pre-read and post-write hooks to a type for side effects or validation. ``` -------------------------------- ### DataFixerBuilder Constructor Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Initializes a new instance of the DataFixerBuilder class. ```APIDOC ## DataFixerBuilder Constructor ### Description Initializes a new instance of the DataFixerBuilder class. ### Method ```java public DataFixerBuilder(int dataVersion) ``` ### Parameters #### Path Parameters - **dataVersion** (int) - Required - The current/maximum data version supported ``` -------------------------------- ### View Factory Method Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md Use this factory method to create a new View instance. It requires a name, input type, output type, and the transformation function. ```java static View create(String name, Type inType, Type outType, Function, Function> function) ``` -------------------------------- ### Get Map Values Extraction Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Extracts all key-value pairs from a map-like value as Dynamics. Returns a DataResult indicating success or failure. ```java public DataResult, Dynamic>> getMapValues() ``` -------------------------------- ### Get Target Type of TypedOptic Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md Retrieves the target type 'T' of a TypedOptic. This represents the type of the data structure after the optic has been applied. ```java public Type tType() ``` -------------------------------- ### Get Source Type of TypedOptic Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md Retrieves the source type 'S' of a TypedOptic. This represents the type of the data structure before the optic is applied. ```java public Type sType() ``` -------------------------------- ### Add Maven Repository Source: https://github.com/mojang/datafixerupper/blob/master/README.md Configure your Maven project to use the Minecraft Libraries repository. ```xml minecraft-libraries Minecraft Libraries https://libraries.minecraft.net ``` -------------------------------- ### Product and Sum Types Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Methods for creating product (and) and sum (or) types. ```APIDOC ## Product and Sum Types ### and() ```java static TypeTemplate and(TypeTemplate first, TypeTemplate second) static TypeTemplate and(TypeTemplate first, TypeTemplate... rest) ``` Creates a product type (tuple/record) combining multiple types. ### or() ```java static TypeTemplate or(TypeTemplate first, TypeTemplate second) static TypeTemplate or(TypeTemplate first, TypeTemplate... rest) ``` Creates a sum type (union/variant) allowing alternative types. ``` -------------------------------- ### Add Gradle Repository Source: https://github.com/mojang/datafixerupper/blob/master/README.md Include this repository in your Gradle build file to access DataFixerUpper. ```groovy maven { url "https://libraries.minecraft.net" } ``` -------------------------------- ### DataResult: Get Partial Result or Throw Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Retrieves the successful or partial result, throwing a custom exception or a default IllegalStateException if no result is available. ```java R getPartialOrThrow(Function exceptionSupplier) throws E R getPartialOrThrow() throws IllegalStateException ``` -------------------------------- ### Create Simple Codec Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md Define a basic codec for a custom type by providing encoder and decoder functions. The decoder maps a string value to a new MyType object. ```java Codec codec = Codec.of( (value, ops, prefix) -> ops.createString(value.toString()), // encoder (ops, input) -> ops.getStringValue(input) // decoder .map(str -> new MyType(str)) .map(obj -> Pair.of(obj, input)) ); ``` -------------------------------- ### Lens Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md A Lens focuses on a single, always-present field within a data structure. It allows for both retrieving (getting) and updating (setting) the value of this field. ```APIDOC ## Lens ### Description Focuses on a single, always-present field. Can get and set. ### Method Signature ```java static Lens lens(Function getter, BiFunction setter) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Description | |-----------|------|-------------| | getter | `Function` | Extracts focus from whole | | setter | `BiFunction` | Updates whole with new focus | ### Request Example ```java Lens nameLens = Optics.lens( Player::getName, (player, name) -> player.withName(name) ); ``` ### Response #### Success Response (200) Not applicable for this static factory method. #### Response Example Not applicable for this static factory method. ``` -------------------------------- ### Lifecycle Management: stable() Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Attaches stability information to a codec, marking it as stable. ```APIDOC ## Lifecycle Management: stable() ### `default Codec stable()` Attaches stability information to codec, marking it as stable. ``` -------------------------------- ### Schema Constructor Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md The Schema constructor initializes a new schema with a version key and an optional parent schema. Subclasses must override registration methods. ```java public Schema(int versionKey, Schema parent) ``` -------------------------------- ### Access Typed Field by Key Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Similar to get(), but maintains type information for chained operations when accessing a field by String key. Returns an OptionalDynamic. ```java public OptionalDynamic getTyped(String key) ``` -------------------------------- ### Select DynamicOps for Different Formats Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md Choose the appropriate DynamicOps instance based on the data format (JSON, plain Java objects, or custom). ```java // For JSON DynamicOps jsonOps = JsonOps.INSTANCE; Dynamic jsonDynamic = new Dynamic<>(jsonOps, jsonElement); // For plain Java objects (Maps, Lists) DynamicOps javaOps = JavaOps.INSTANCE; Dynamic javaDynamic = new Dynamic<>(javaOps, javaMap); // Custom format DynamicOps customOps = new MyCustomDynamicDynamicOps(); Dynamic customDynamic = new Dynamic<>(customOps, customValue); ``` -------------------------------- ### Traversal Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md A Traversal focuses on multiple elements, typically a list of values, within a data structure. It enables getting and setting all elements or mapping transformations over them. ```APIDOC ## Traversal ### Description Focuses on multiple elements (list of values). Can get/set all or map over them. ### Method Signature ```java static Traversal traversal(Function> getter, BiFunction, S> setter) ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Description | |-----------|------|-------------| | getter | `Function>` | Extracts list of elements | | setter | `BiFunction, S>` | Updates structure with a new list of elements | ### Request Example None provided in source. ### Response #### Success Response (200) Not applicable for this static factory method. #### Response Example Not applicable for this static factory method. ``` -------------------------------- ### Basic DataFix Template Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md A template for creating a custom DataFix class, including constructor and the makeRule method. ```java public class MyDataFix extends DataFix { public MyDataFix(Schema outputSchema, boolean changesType) { super(outputSchema, changesType); } @Override protected TypeRewriteRule makeRule() { Type inputType = getInputSchema().getType(() -> "MyData"); Type outputType = getOutputSchema().getType(() -> "MyData"); return fixTypeEverywhere( "my_fix_name", inputType, outputType, ops -> oldValue -> transformValue(oldValue) ); } private T transformValue(T value) { // Transformation logic return value; } } ``` -------------------------------- ### Configuring DataFixerUpper Logging Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/README.md Configure logging levels for DataFixerUpper and serialization packages using SLF4J/Logback. Set the logger name and desired level (e.g., DEBUG, INFO). ```xml ``` -------------------------------- ### Get Type by Reference Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md The getType() method retrieves a type by its reference. For recursive types, it returns the unwrapped type. An IllegalArgumentException is thrown if the type name is not registered. ```java public Type getType(DSL.TypeReference type) ``` -------------------------------- ### Codec Factory Methods Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Static methods to create Codec instances from provided encoders and decoders. ```APIDOC ## Codec Factory Methods ### `static Codec of(Encoder encoder, Decoder decoder)` Creates a Codec from an Encoder and a Decoder. ### `static Codec of(Encoder encoder, Decoder decoder, String name)` Creates a Codec with a specific name from an Encoder and a Decoder. ### `static MapCodec of(MapEncoder encoder, MapDecoder decoder)` Creates a MapCodec from a MapEncoder and a MapDecoder. ``` -------------------------------- ### Convert Field Type in DataFix Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/examples.md Example of changing a field's type using the write-fix-read pattern. This is useful for migrating data types like converting Health to a double. ```java public class ConvertFieldTypeFix extends DataFix { public ConvertFieldTypeFix(Schema outputSchema) { super(outputSchema, true); // Changes type } @Override protected TypeRewriteRule makeRule() { return writeFixAndRead("convert_health_to_double", getInputSchema().getType(() -> "Entity"), getOutputSchema().getType(() -> "Entity"), dynamic -> { // dynamic is the serialized form with old type OptionalDynamic health = dynamic.get("Health"); return health.result() .map(num -> dynamic.set("Health", num.doubleValue())) .orElse(dynamic); } ); } } ``` -------------------------------- ### Serialization and Dynamic APIs Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/MANIFEST.txt Documentation for serialization and dynamic data handling APIs, including codecs and dynamic operations. ```APIDOC ## Serialization and Dynamic APIs ### Description This section provides reference for the serialization and dynamic data handling capabilities within DataFixerUpper. It includes details on codecs, `DynamicOps`, and related utilities for flexible data serialization. ### Method N/A (Documentation Reference) ### Endpoint N/A (Documentation Reference) ### Parameters N/A (Documentation Reference) ### Request Example N/A (Documentation Reference) ### Response N/A (Documentation Reference) ``` -------------------------------- ### Schema Constructor Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md The `Schema` constructor initializes a new schema with a version key and an optional parent schema. Subclasses must override registration methods to define the types, entities, and block entities for this schema. ```APIDOC ## Schema Constructor ### Description Initializes a new schema with a version key and an optional parent schema. Subclasses must override registration methods to define the types, entities, and block entities for this schema. ### Method ```java public Schema(int versionKey, Schema parent) ``` ### Parameters #### Path Parameters - **versionKey** (`int`) - Required - Encoded version (version << 16 | subVersion) - **parent** (`Schema`) - Required - Parent schema for inheritance (null for first) ``` -------------------------------- ### DynamicOps: Get Typed Values Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Extracts values as specific types (number, string, boolean) from a given native format value. Returns a DataResult indicating success or failure. ```java DataResult getNumberValue(T input) DataResult getStringValue(T input) DataResult getBooleanValue(T input) ``` -------------------------------- ### View Properties Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md These methods retrieve metadata and the core function from a View instance. The name is for logging, inType and outType define the transformation's signature, and function is the actual transformation logic. ```java public String name() ``` ```java public Type inType() ``` ```java public Type outType() ``` ```java public Function, Function> function() ``` -------------------------------- ### Get Type Identifier Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/types-and-schema.md The id() method returns the type identifier for a given type name. For recursive types, it returns an index reference; otherwise, it returns the full template. ```java public TypeTemplate id(String name) ``` -------------------------------- ### Dynamic Constructor Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Constructs a Dynamic wrapper with a specified DynamicOps handler and an optional initial value. ```java public Dynamic(DynamicOps ops) public Dynamic(DynamicOps ops, T value) ``` -------------------------------- ### DataFixerBuilder Constructor Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md Initializes a DataFixerBuilder with the current or maximum supported data version. Versions exceeding this will be logged as warnings. ```java DataFixerBuilder builder = new DataFixerBuilder(int dataVersion) ``` -------------------------------- ### Lifecycle Management: deprecated() Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Attaches lifecycle information to a codec, marking it as deprecated since a specific version. ```APIDOC ## Lifecycle Management: deprecated() ### `default Codec deprecated(int since)` Attaches stability information to codec, marking it as deprecated since a specific version. ``` -------------------------------- ### Inspect DataResult Error State Safely Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/errors.md Safely inspect a DataResult for errors without throwing exceptions. Use `error()` to get an Optional of the error details, or `resultOrPartial()` to extract the value or log partial errors. ```java DataResult result = ...; // May be success or error // Safe error inspection: Optional> maybeError = result.error(); if (maybeError.isPresent()) { String message = maybeError.get().message(); Optional partial = maybeError.get().getPartialResult(); // Handle partial result if available } // Or use resultOrPartial() with logging: Optional value = result.resultOrPartial(System.err::println); ``` -------------------------------- ### Composition: optional() Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Creates codecs for optional fields, with support for default values. ```APIDOC ## Composition: optional() ### `default Codec> optionalFieldOf(String name, A defaultValue)` Creates a codec for an optional field with a specified default value. ### `default Codec> optionalFieldOf(String name)` Creates a codec for an optional field without a default value. ``` -------------------------------- ### DataFixerBuilder Constructor Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Initializes a new DataFixerBuilder with the specified data version. ```java public DataFixerBuilder(int dataVersion) ``` -------------------------------- ### Attaching Lifecycle to Codecs Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/README.md Mark codecs as stable or deprecated using these methods. `stable()` marks a codec as stable, while `deprecated(version)` marks it as deprecated since a specific version. ```java codec.stable() codec.deprecated(version) ``` -------------------------------- ### Product Type Creation Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Creates a product type (tuple/record) by combining multiple types. ```java static TypeTemplate and(TypeTemplate first, TypeTemplate second) static TypeTemplate and(TypeTemplate first, TypeTemplate... rest) ``` -------------------------------- ### Dispatching Codec Based on Type Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Creates a codec that dispatches to different codecs based on a discriminator field. This is useful for handling polymorphic types. ```java static Codec dispatch(String name, Function type, Function> codec) ``` ```java Codec animalCodec = Codec.dispatch( "type", animal -> animal, // discriminator function obj -> switch(obj) { case Dog dog -> DOG_CODEC; case Cat cat -> CAT_CODEC; } ); ``` -------------------------------- ### Container Types Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Methods for creating list and compound list types. ```APIDOC ## Container Types ### list() ```java static TypeTemplate list(TypeTemplate element) static List.ListType list(Type first) ``` Creates a list type with uniform element type. ### compoundList() ```java static TypeTemplate compoundList(TypeTemplate element) static CompoundList.CompoundListType compoundList(Type value) static TypeTemplate compoundList(TypeTemplate key, TypeTemplate element) static CompoundList.CompoundListType compoundList(Type key, Type value) ``` Creates a map-like structure with key-value pairs. ``` -------------------------------- ### Type Conversion: dispatch() Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Creates a codec that dispatches to different codecs based on a discriminator field. ```APIDOC ## Type Conversion: dispatch() ### `static Codec dispatch(String name, Function type, Function> codec)` Creates a codec that dispatches to different codecs based on a discriminator field. This is useful for handling polymorphic types where the specific subtype needs to be determined before decoding. **Example:** ```java Codec animalCodec = Codec.dispatch( "type", animal -> animal, // discriminator function obj -> switch(obj) { case Dog dog -> DOG_CODEC; case Cat cat -> CAT_CODEC; } ); ``` ``` -------------------------------- ### Composition: flatXmap() Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Similar to xmap, but allows transformations to fail and return a DataResult. ```APIDOC ## Composition: flatXmap() ### `default Codec flatXmap(Function> to, Function> from)` Like xmap but allows transformations to fail. This method is useful when the conversion between types might result in an error, which can be represented by a `DataResult`. ``` -------------------------------- ### Build DataFixer Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/datafixer-main.md Constructs and returns the final optimized DataFixer, wrapped in a Result object that supports asynchronous optimization. ```java public Result build() ``` -------------------------------- ### Core DataFix APIs Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/MANIFEST.txt Documentation for the core DataFixer APIs, covering essential functionalities for data manipulation and transformation. ```APIDOC ## Core DataFix APIs ### Description This section details the core APIs for DataFixerUpper, focusing on the `DataFixer` interface and related components used for applying data transformations. ### Method N/A (Documentation Reference) ### Endpoint N/A (Documentation Reference) ### Parameters N/A (Documentation Reference) ### Request Example N/A (Documentation Reference) ### Response N/A (Documentation Reference) ``` -------------------------------- ### Type System and Schema APIs Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/MANIFEST.txt Reference for the type system and schema definition APIs, enabling users to define and manipulate data structures. ```APIDOC ## Type System and Schema APIs ### Description This section covers the APIs related to DataFixerUpper's type system and schema definitions. It explains how to define, represent, and work with various data types and schemas. ### Method N/A (Documentation Reference) ### Endpoint N/A (Documentation Reference) ### Parameters N/A (Documentation Reference) ### Request Example N/A (Documentation Reference) ### Response N/A (Documentation Reference) ``` -------------------------------- ### Create a Record Codec Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/types.md Use RecordCodecBuilder to construct codecs for record-like classes. This involves defining fields and applying them to a constructor. ```java static RecordCodecBuilder of(Function, T>> function) static Group group(List, ? extends A>> fields) static Partial point(A value) // Used in chains like: RecordCodecBuilder.create(instance -> instance.group( Codec.STRING.fieldOf("name").forGetter(Person::getName), Codec.INT.fieldOf("age").forGetter(Person::getAge) ).apply(instance, Person::new)) ``` -------------------------------- ### Compose Optics Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/optics.md Optics can be composed together to navigate through nested data structures. This method combines two existing optic instances. ```java Optics.compose(outerOptic, innerOptic) ``` -------------------------------- ### Composition: xmap() Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Transforms between two types bidirectionally using mapping functions. ```APIDOC ## Composition: xmap() ### `default Codec xmap(Function to, Function from)` Transforms between two types bidirectionally. This method allows you to create a new Codec that operates on a different type by providing functions for converting between the original type and the new type. **Example:** ```java Codec intCodec = // ... Codec durationCodec = intCodec.xmap( millis -> Duration.ofMillis(millis), duration -> (int) duration.toMillis() ); ``` ``` -------------------------------- ### Composition: listOf() Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/api-reference/serialization.md Creates a codec for lists of the current type. ```APIDOC ## Composition: listOf() ### `default Codec> listOf()` Creates a codec for lists of the type. This allows you to easily serialize and deserialize collections of elements. ``` -------------------------------- ### Point-Free Optimization Rule Placeholder Source: https://github.com/mojang/datafixerupper/blob/master/_autodocs/configuration.md This is a placeholder for the PointFreeRule used for optimization. The library automatically applies optimizations like catamorph fusion, lens composition merging, and projection sorting. ```java protected static final PointFreeRule OPTIMIZATION_RULE = /* ... */; ```