All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.fxmisc.richtext.model.SuperCodec Maven / Gradle / Ivy

package org.fxmisc.richtext.model;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Codec that can serialize an object and its super class; helpful when using generics and captures.
 *
 * @param  the super class type
 * @param  the regular class type
 */
interface SuperCodec extends Codec {
    void encodeSuper(DataOutputStream os, S s) throws IOException;

    @Override
    default void encode(DataOutputStream os, T t) throws IOException {
        encodeSuper(os, t);
    }

    /**
     * Returns a codec that can serialize {@code sc}'s type's super class
     */
    @SuppressWarnings("unchecked")
    static  SuperCodec upCast(SuperCodec sc) {
        return (SuperCodec) sc;
    }

    static  SuperCodec, List> collectionListCodec(Codec elemCodec) {
        return new SuperCodec, List>() {

            @Override
            public String getName() {
                return "list<" + elemCodec.getName() + ">";
            }

            @Override
            public void encodeSuper(DataOutputStream os, Collection col) throws IOException {
                os.writeInt(col.size());
                for(T t: col) {
                    elemCodec.encode(os, t);
                }
            }

            @Override
            public List decode(DataInputStream is) throws IOException {
                int size = is.readInt();
                List elems = new ArrayList<>(size);
                for(int i = 0; i < size; ++i) {
                    T t = elemCodec.decode(is);
                    elems.add(t);
                }
                return elems;
            }
        };
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy