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

org.fxmisc.richtext.Codec Maven / Gradle / Ivy

There is a newer version: 0.11.3
Show newest version
package org.fxmisc.richtext;

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

public interface Codec {

    String getName();
    void encode(DataOutputStream os, T t) throws IOException;
    T decode(DataInputStream is) throws IOException;


    static final Codec STRING_CODEC = new Codec() {

        @Override
        public String getName() {
            return "string";
        }

        @Override
        public void encode(DataOutputStream os, String s) throws IOException {
            os.writeUTF(s);
        }

        @Override
        public String decode(DataInputStream is) throws IOException {
            return is.readUTF();
        }
    };

    static  Codec> listCodec(Codec elemCodec) {
        return SuperCodec.collectionListCodec(elemCodec);
    }
}

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);
    }

    @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