001/*
002 * Copyright 2022-2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.soklet.converter;
018
019import org.jspecify.annotations.NonNull;
020import org.jspecify.annotations.Nullable;
021
022import java.lang.reflect.Type;
023import java.util.Optional;
024
025/**
026 * Contract for converting objects from one type to another.
027 * <p>
028 * For example, you might have a {@code ValueConverter<String, List<Integer>>} which converts
029 * text like {@code "1,2,3"} to a list of numbers.
030 * <p>
031 * Generic type inference only supports direct {@link AbstractValueConverter} / {@link FromStringValueConverter}
032 * subclasses or direct {@link ValueConverter} implementations. If you introduce intermediate generic base classes
033 * or type variables (for example, {@code abstract class BadConverter<T> extends AbstractValueConverter<String, T>} then
034 * {@code class JwtConverter extends BadConverter<Jwt>}), Soklet may be unable to resolve {@code F}/{@code T} and will
035 * throw an {@link IllegalStateException}. This limitation may be addressed in a future release.
036 * <p>
037 * Value conversion is documented in detail at <a href="https://www.soklet.com/docs/value-conversions">https://www.soklet.com/docs/value-conversions</a>.
038 *
039 * @author <a href="https://www.revetkn.com">Mark Allen</a>
040 */
041public interface ValueConverter<F, T> {
042        /**
043         * Converts {@code from} to an instance of {@code T}.
044         *
045         * @param from the value from which to convert. May be {@code null}
046         * @return the {@code T} representation of {@code from}
047         * @throws ValueConversionException if an error occurs during conversion
048         */
049        @NonNull
050        Optional<T> convert(@Nullable F from) throws ValueConversionException;
051
052        /**
053         * The 'converting from' type.
054         *
055         * @return the type represented by {@code F}
056         */
057        @NonNull
058        Type getFromType();
059
060        /**
061         * The 'converting to' type.
062         *
063         * @return the type represented by {@code T}
064         */
065        @NonNull
066        Type getToType();
067}