001/* 002 * Configurate 003 * Copyright (C) zml and Configurate contributors 004 * 005 * Licensed under the Apache License, Version 2.0 (the "License"); 006 * you may not use this file except in compliance with the License. 007 * You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.spongepowered.configurate.extra.dfu.v3; 018 019import static java.util.Objects.requireNonNull; 020 021import com.mojang.serialization.Codec; 022import com.mojang.serialization.Lifecycle; 023import io.leangen.geantyref.TypeToken; 024import org.checkerframework.checker.nullness.qual.Nullable; 025import org.spongepowered.configurate.serialize.TypeSerializer; 026import org.spongepowered.configurate.serialize.TypeSerializerCollection; 027 028/** 029 * A bridge between Configurate and DataFixerUpper serialization systems. 030 * 031 * @since 4.0.0 032 */ 033public final class DfuSerializers { 034 035 private DfuSerializers() { 036 } 037 038 /** 039 * Create a new serializer wrapping the provided {@link Codec}. 040 * 041 * @param codec codec to use for the serialization operation 042 * @param <V> value type 043 * @return a new serializer 044 * @since 4.0.0 045 */ 046 public static <V> TypeSerializer<V> serializer(final Codec<V> codec) { 047 return new CodecSerializer<>(requireNonNull(codec, "codec")); 048 } 049 050 /** 051 * Create a new codec that uses the default type serializer collection 052 * to serialize an object of the provided type. 053 * 054 * @param type token representing a value type 055 * @param <S> value type 056 * @return a codec for the type, or null if an appropriate 057 * {@link TypeSerializer} could not be found. 058 * @since 4.0.0 059 */ 060 public static <S> @Nullable Codec<S> codec(final TypeToken<S> type) { 061 return codec(requireNonNull(type, "type"), TypeSerializerCollection.defaults()); 062 } 063 064 /** 065 * Create a new codec based on a Configurate {@link TypeSerializer}. 066 * 067 * @param type type to serialize 068 * @param collection source for values 069 * @param <V> value type 070 * @return a codec, or null if an appropriate {@link TypeSerializer} 071 * could not be found for the TypeToken. 072 * @since 4.0.0 073 */ 074 public static <V> @Nullable Codec<V> codec(final TypeToken<V> type, final TypeSerializerCollection collection) { 075 final @Nullable TypeSerializer<V> serial = collection.get(requireNonNull(type, "type")); 076 if (serial == null) { 077 return null; 078 } 079 return new TypeSerializerCodec<>(type, serial, ConfigurateOps.forSerializers(collection)).withLifecycle(Lifecycle.stable()); 080 } 081 082}