001/*
002 * SPDX-License-Identifier: Apache-2.0
003 *
004 * Copyright 2024-2026 The Enola <https://enola.dev> Authors
005 *
006 * Licensed under the Apache License, Version 2.0 (the "License");
007 * you may not use this file except in compliance with the License.
008 * You may obtain a copy of the License at
009 *
010 *     https://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package dev.enola.common.convert;
019
020import com.google.errorprone.annotations.Immutable;
021
022import java.io.IOException;
023import java.util.Optional;
024
025/**
026 * Converts objects of type T to &amp; from String, if it can.
027 *
028 * @param <T> the type of objects to convert
029 */
030@Immutable
031public interface ObjectToStringBiConverter<T>
032        extends BiConverter<T, String>, ConverterIntoAppendable<T>, ObjectClassConverter<T> {
033
034    @Override
035    default boolean convertInto(T from, Appendable into) throws ConversionException, IOException {
036        into.append(this.convertTo(from));
037        return true;
038    }
039
040    @Override
041    @SuppressWarnings("unchecked")
042    // TODO Remove throws IOException again (together with rm from super type)
043    default <X> Optional<X> convertToType(T input, Class<X> type) throws IOException {
044        // See also ObjectConverter's & other similar convertToType() implementations
045        // TODO Re-consider class.equals -VS- isAssignableFrom, here & in ObjectConverter
046        if (input != null && String.class.equals(type))
047            return (Optional<X>) Optional.of(convertTo(input));
048        return Optional.empty();
049    }
050
051    @SuppressWarnings("unchecked")
052    default <X> Optional<X> convertObjectToType(Object input, Class<X> type) throws IOException {
053        return convertToType((T) input, type);
054    }
055}